﻿// Name:        Doo.WebUI.core.debug.js
// Assembly:    Doo
// Version:     2.1.0.785
// FileVersion: 2.1.0.0
/// <reference name="MicrosoftAjax.js"/>

/* 浏览器兼容层 */
//localStorage
(function () {
    var convertto = function (obj) {
        if (typeof (obj) == 'string') {
            //不进行JSON转义
            if (obj.charAt(0) == '{' || obj.charAt(0) == '*') return '*' + obj;
            return obj;
        }
        else {
            return Sys.Serialization.JavaScriptSerializer.serialize(obj);
        }
    };
    var convertfrom = function (str) {
        if (!str) return "";
        if (str.charAt(0) == '{' || str.charAt(0) == '[') {
            return Sys.Serialization.JavaScriptSerializer.deserialize(str);
        }
        else if (str.charAt(0) == '*') {
            return str.substr(1);
        }
        else {
            return str;
        }
    };
    if (!('localStorage' in window)) {
        window.localStorage = (function () {
            var documentElement, isIE = !!document.all;

            if (isIE) {
                documentElement = document.documentElement;
                documentElement.addBehavior('#default#userdata');
                return {
                    setItem: function (key, value) {
                        documentElement.setAttribute('value', value);
                        documentElement.save(key);
                    },
                    getItem: function (key) {
                        documentElement.load(key);
                        return documentElement.getAttribute('value');
                    },
                    removeItem: function (key) {
                        documentElement.removeAttribute('value');
                        documentElement.save(key);
                    }
                }
            }

            return {
                setItem: function (key, value) {
                    /// <param name="key" type="String">Cache Key</param>
                    /// <param name="value" type="Object"></param>
                    window.globalStorage[location.hostname][key] = value;
                },
                getItem: function (key) {
                    /// <param name="key" type="String">Cache Key</param>
                    return window.globalStorage[location.hostname][key];
                },
                removeItem: function (key) {
                    /// <param name="key" type="String">Cache Key</param>
                    window.globalStorage[location.hostname].removeItem(key);
                }
            };
        })();
    }
    window['localStorageEx'] = {
        setItem: function (key, value) {
            localStorage.setItem(key, convertto(value));
        },
        getItem: function (key, value) {
            return convertfrom(localStorage.getItem(key));
        },
        removeItem: function (key) {
            localStorage.removeItem(key);
        }
    }
})();
/* FF扩展 */
if (Sys.Browser.agent == Sys.Browser.Firefox) {
    HTMLElement.prototype.moveRow = function (indexFrom, indexTo) {
        if (!this.rows) return;
        var l = this.rows.length;
        if (!l) return;
        if (indexFrom == indexTo) return;
        var rFrom = this.rows[indexFrom];
        var isLast = indexTo == l;
        this.removeChild(rFrom);
        if (isLast) {
            this.appendChild(rFrom);
        }
        else {
            this.insertBefore(rFrom, this.rows[indexTo]);
        }
    }
    HTMLOptionsCollection.prototype.removeChild = function (op) {
        this.remove(op);
    }
}
/* 基础类型扩展 */
Object.createSelector = function (name) {
    return function (obj) { return obj[name]; };
}
Array.prototype.sum = function (delegate) {
    ///<summary>计算合计值，支持单个及多个值计算</summary>
    ///<param name="delegate" type="Function">选择函数</param>
    var l = this.length;
    var s = 0, i = 1, n;
    if (delegate) {
        var r = delegate(this[0]);
        if (r instanceof Object) {
            s = {};
            for (n in r) s[n] = r[n];
            while (i < l) {
                r = delegate(this[i++]);
                for (n in r) s[n] += r[n];
            }
        }
        else {
            s = r;
            while (i < l) {
                s += delegate(this[i++]);
            }
        }
        return s;
    }
    for (i = 0; i < l; i++) { s += this[i]; }
    return s;
};
Type.hasType = function (typeName, ns) {
    try {
        if (typeof (Type.parse(typeName, ns)) == 'undefined') return false;
        return true;
    }
    catch (e) {
        return false;
    }
}

Type.registerNamespace("Doo");

Doo.Utils =
{
    Cookie:
    {
        get_value: function (key) {
            /// <param name="key" type="String">Cookie Key</param>
            var allcookies = document.cookie;
            var cookie_pos = allcookies.indexOf(key);

            // 如果找到了索引，就代表cookie存在，
            // 反之，就说明不存在。
            if (cookie_pos != -1) {
                // 把cookie_pos放在值的开始，只要给值加1即可。
                cookie_pos += key.length + 1;
                var cookie_end = allcookies.indexOf(";", cookie_pos);

                if (cookie_end == -1) {
                    cookie_end = allcookies.length;
                }

                var value = unescape(allcookies.substring(cookie_pos, cookie_end));
            }

            return value;

        }
    },

    KeyValueString:
    {
        get_value: function (str, key) {///<summary>获取键值对字符串中指定key的值</summary>
            /// <param name="str" type="String">The String which get keyvalue from</param>
            /// <param name="key" type="String">Key</param>
            var find = key + "=";
            var i = 0;
            for (; ; ) {
                i = str.indexOf(find);
                if (i < 0) return null;
                if (i == 0 || str.charAt(i - 1) == '&') break;
                i = i + find.length;
            };
            var end = str.indexOf('&');
            if (end < 0) end = str.length + 1;
            return unescape(str.substring(i + find.length, end));
        }
    },

    ListAction:
    {
        singlecheck: function (elem, className) {
            /// <param name="elem" DomElement="true"></param>
            /// <param name="className" type="String">CssClass Name</param>
            if (!className) className = "checked";

            var list = elem.parentNode;
            var checkObj = list['checkObj'];
            if (!checkObj) {
                var checkIndex = list['checkindex'];
                if (checkIndex) checkObj = list.children[checkIndex];
            }

            if (checkObj == elem) return;
            if (checkObj != null) Sys.UI.DomElement.removeCssClass(checkObj, className);
            Sys.UI.DomElement.addCssClass(elem, className);

            list['checkObj'] = elem;
        },

        multicheck: function (elem, className) {
            /// <param name="elem" DomElement="true"></param>
            /// <param name="className" type="String">CssClass Name</param>
            if (!className) className = "checked";

            var hasClass = Sys.UI.DomElement.containsCssClass(elem, className);
            var cssAction = hasClass ? Sys.UI.DomElement.removeCssClass : Sys.UI.DomElement.addCssClass;
            cssAction(elem, className);
        }
    },

    Form: {
        BuildQuery: function (root) {
            ///<summary>创建查询字符串</summary>
            var nodes = root.childNodes;
            var query = {};
            for (var i = 0; i < nodes.length; i++) {
                var node = nodes[i];
                if (node.nodeType != 1) continue;
                var name = node.getAttribute('field');
                if (!name) continue;
                var value = node.value;
                if (node.control && node.control.get_code) value = node.control.get_code(); //取code
                query[name] = value;
            };
            return query;
        }
    },

    QueryString: ///<summary>查询字符串构造</summary>
    (function () {
        var Sys_QueryString = function () { };
        Sys_QueryString.prototype = {
            _query: "",
            _queryArray: {},
            toString: function (additonArgs) {
                if (!additonArgs) return this._query;
                var qa = [];
                for (var name in this._queryArray) {
                    if (name in additonArgs) {
                        qa.push(name + "=" + encodeURI(additonArgs[name]));
                        additonArgs[name] = null;
                    }
                    else {
                        qa.push(this._queryArray[name]);
                    }
                }
                for (var name in additonArgs) {
                    if (additonArgs[name] != null) {
                        qa.push(name + "=" + encodeURI(additonArgs[name]));
                    }
                }
                return "?" + qa.join("&");
            },
            add_para: function (name, value) {
                this._queryArray[name] = name + "=" + encodeURI(value);
            },
            add_paras: function (args) {
                for (var name in args) { this._queryArray[name] = name + "=" + encodeURI(args[name]); ; }
            },
            remove_para: function (name) {
                if (name in this._queryArray) { delete this._queryArray[name]; }
            },
            get_para: function (name) {
                var v = this._queryArray[name]; if (!v) return null;
                var i = v.indexOf('=');
                return v.substr(i + 1);
            },
            set_para: function (name, value) {
                return this.add_para(name, value);
            },
            clone: function () {
                ///<summary>复制一个新对象以处理</summary>
                var newthis = new Sys_QueryString();
                newthis._query = this._query;
                newthis._queryArray = this._queryArray;
                return newthis;
            },
            init: function (query) {
                query = query != null ? query : location.search;
                this._queryArray = {};
                this._query = query;
                if (query.charAt(0) == "?") query = query.substr(1);
                if (query.length == 0) return;
                var oqs = query.split("&");
                var i = 0;
                while (i < oqs.length) {
                    var ei = oqs[i].indexOf("=");
                    if (ei >= 0) {
                        this._queryArray[oqs[i].substr(0, ei)] = oqs[i];
                    }
                    else {
                        this._queryArray[oqs[i]] = oqs[i];
                    }
                    i++;
                }
            }
        };
        var globalQ = new Sys_QueryString();
        globalQ.init();
        return globalQ;
    })(),

    Hash: {
        get_hash: function () {
            ///<summary>获取带#号的值</summary>
            var s = location.href;
            var i = s.indexOf('#');
            if (i < 0) return '';
            else return s.substr(i);
        }
    }, //Hash帮助，支持设置和获取hash值，支持对hash值监听

    Dom:
    {
        createElement: function (html, callback) {
            var temp = document.createElement('div'), frag = document.createDocumentFragment();
            temp.innerHTML = html;
            (function () {
                if (temp.firstChild) {
                    frag.appendChild(temp.firstChild);
                    setTimeout(arguments.callee, 0);
                } else {
                    callback(frag);
                }
            })();
        },
        setHtmlAsync: function (elem, html, callback) {
            /// <summary>异步设置html，提高效率</summary>
            /// <param name="elem" DomElement="true">要设置innerHTML的元素</param>
            /// <param name="html" type="String">HTML内容</param>
            /// <param name="callback" type="Function">设置成功后的回调</param>
            Doo.Utils.Dom.createElement(html, function (frag) {
                elem.innerHTML = "";
                elem.appendChild(frag);
                if (callback) callback(elem);
            });
        },
        checkTagName: function (elem, tag, scope) {
            /// <summary>检查是否是指定名字空间的指定标签</summary>
            /// <param name="tag" type="String">小写的标签</param>
            if (!elem || !elem.tagName) return false; //没有标签
            var tn = elem.tagName.toLowerCase();
            if (!scope) if (tn != tag) return false; else scope = ""; //没有名字空间且标签不对应

            var so = elem.scopeName;
            //有名字空间
            if (so) {
                return scope == so.toLowerCase(); //名字空间不对应
            }
            else {//部分浏览器是嵌入到了tagName里面
                return (scope + ':' + tag) == tn;
            }
        },
        getScopeName: function (elem) {
            /// <summary>返回小写的名字空间</summary>
            if (!elem || !elem.tagName) return null;
            if (elem.scopeName) return elem.scopeName.toLowerCase();
            var i = elem.tagName.indexOf(':');
            if (i < 0) return null;
            return elem.tagName.substring(0, i - 1).toLowerCase();
        },
        getFullTag: function (elem) {
            ///<summary>返回完整的标签</summary>
            if (elem.scopeName) return (elem.scopeName + ':' + (elem.localName || elem.tagName)).toLowerCase();
            else return elem.tagName.toLowerCase();
        }
    },

    eval: function (context, statments) {
        with (context) {
            return eval(statments);
        }
    }
};
Doo.Utils.Ajax = (function () {
    var defaultSite = null;
    var randp = function () { return new Date().setFullYear(1991); };
    var _frameParent = null;
    var timeoutstatus = 504;
    var _createUCFrame = function (p) {
        if (_frameParent == null) {
            _frameParent = document.createElement("div");
            document.body.insertBefore(_frameParent, document.body.firstChild);
        };
        var ifmid = 'UC_FRAME' + (p || '');
        var ifm = window[ifmid];
        if (!ifm) {
            ifm = document.createElement("iframe");
            ifm.style.width = 0;
            ifm.style.height = 0;
            ifm.frameBorder = 0;
            _frameParent.appendChild(ifm);
            window[ifmid] = ifm;
        }
        return ifm;
    };
    var _destoryUCFrame = function (p) {
        var ifmid = 'UC_FRAME' + (p || '');
        var ifm = window[ifmid];
        if (ifm) {
            ifm.parentNode.removeChild(ifm);
            window[ifmid] = null;
        }
    };
    var _crossAjax = function (args) {
        ///<summary>跨域获取数据</summary>
        ///<param name="args">参数，包括uniqueid,url,params,method,onsucc,onfail,callbackname,timeup</param>
        var uniqueid = args.uniqueid || randp();
        var ifm = _createUCFrame(uniqueid);
        if (ifm['onsucc']) return;

        var callbackname = args.callbackname || ("crosscallback" + uniqueid);
        var method = args.method || 'post';

        var parambuilder = [];
        var p = args.params;
        var u = args.url;
        var host = location.host;
        var ui = u.indexOf('?');

        if (method == 'get') {

            //处理get参数
            if (!p) p = { host: host, callbackname: callbackname };
            else if (!p.host) { p.host = host; p.callbackname = callbackname; }
            if (ui > 0) {
                var ps = u.substring(ui + 1).split('&');
                if (ps && ps.length > 0) {
                    for (var i = 0; i < ps.length; i++) {
                        var j = ps[i].indexOf('=');
                        p[ps[i].substring(0, j)] = ps[i].substring(j + 1);
                    }
                }
            }
        }
        else {//post
            u += (ui >= 0 ? '&' : '?') + 'host=' + host + '&callbackname=' + callbackname;
        }
        if (p) {
            for (var n in p) {
                parambuilder.push(String.format("<input type='text' name='{0}' value='{1}'/>", n, p[n]));
            }
        }

        var doc = ifm.contentWindow.document;
        doc.open();
        doc.write("<html><head></head><body><form method='" + method + "' action='" + u + "'>" +
		parambuilder.join('') +
		"<button type='submit'></button></form></body></html>");
        doc.close();

        var timeout = (args.timeout || 10) * 1000;
        var onfail = args.onfail;
        var onsucc = args.onsucc;
        var persist = args.persist;

        var failTimer = setTimeout(function () {
            if (onfail) { onfail(timeoutstatus); }
            _destoryUCFrame(uniqueid);
        }, timeout);
        var succFunc = function () {
            clearTimeout(failTimer);
            if (onsucc) { onsucc.apply(window, arguments); }
            if (!persist) _destoryUCFrame(uniqueid);
        }
        window[callbackname] = succFunc;

        doc.forms[0].submit();
        return uniqueid;
    };

    var _clearAjax = function (id) {
        //清除id对应的，如果有的话
        _destoryUCFrame(id);
    };

    return {
        set_defaultSite: function (v) {
            defaultSite = v;
        },
        get_defaultSite: function () {
            return defaultSite;
        },
        istimeout: function (s) { return s == timeoutstatus; },
        crossAjax: _crossAjax,
        clearAjax: _clearAjax
    };
})();



Doo.Delegate = function (func, obj) {
    /// <param name="func" type="Function"></param>
    /// <param name="obj" type="Object">The Object This Point Reference To</param>
    return function () { return func.apply(obj, arguments); };
}

/* 增加css样式 */
Doo.Css = {
    _imported: {},
    getSheet: function () {
        var sss = document.styleSheets;
        if (sss.length == 0) {
            var elem = document.createElement("style");
            elem.type = "text/css";
            document.body.appendChild(elem);
        }
        var sheet = sss[0];
        return sheet.sheet || sheet; //兼容部分浏览器
    },
    importCss: function (url) {
        if (this._imported[url]) return;

        this.getSheet().addImport(url);
        this._imported[url] = true;
    },
    addCssRule: function (selector, cssText) {
        ///<summary>设置CSS规则</summary>
        ///<param name="selector" type="String">选择符</param>
        ///<param name="cssText" type="String">要设置的规则</param>
        ///<returns>FF下返回新规则的序号</returns>
        var sheet = this.getSheet();
        var rules = sheet.cssRules || sheet.rules;
        var r = rules[selector];
        return sheet.addRule ? sheet.addRule(selector, cssText) : sheet.insertRule(selector + '{' + cssText + '}', sheet.cssRules.length);
    }
};
Doo.Resources = {
    RegCss: function (key, path) {
        /// <param name="key" type="String"></param>
        /// <param name="path" type="String"></param>
        var cssid = "Doo_CSS_" + key;
        if ($get(cssid)) return;
        var elem = document.createElement("link");
        elem.type = "text/css";
        elem.rel = "stylesheet";
        elem.src = path;
        document.body.appendChild(elem);
    }
}

Doo.Scripts =
{
    SetEvents: function (obj, events) {
        /// <param name="obj" type="Object">object which set events on</param>
        /// <param name="events" type="Object">a hasharray</param>
        /// <summary>设置事件，注意，对象必须在Sys.load事件之前拥有__handlerList属性</summary>
        // 对象中只有一个__handlerList，对于Control来说，就是ControlBase.prototype.__handlerList
        // if (!obj['__handlerList']) obj['__handlerList'] = new Sys.EventHandlerList();
        if (events instanceof Array) {
            Array.forEach(events, function (name) { this._SetEventItem(obj, name); }, this);
        }
        else {
            for (var name in events) {
                this._SetEventItem(obj, name, events[name]);
            }
        }
    },
    _SetEventItem: function (obj, name, handlers) {
        if (!obj['add_' + name]) {
            //此处用this指针的__handlerList，每个对象的事件相互隔离
            obj['add_' + name] = function (handler) { this.__handlerList.addHandler(name, handler); };
            obj['remove_' + name] = function (handler) { this.__handlerList.removeHandler(name, handler); };
            obj['on' + name] = function () { var h = this.__handlerList.getHandler(name); if (h != null) h.apply(this, arguments); };
        }
        if (Array.isInstanceOfType(handlers)) {
            //注册，使init时再转换events
            this.eventinits.push(function () { Doo.Scripts.InitObjEvents(obj, name, handlers); });
        };
    },
    InitObjEvents: function (obj, name, handlers) {
        var scripts = obj.get_scripts() || window;
        var ____hh;
        var events = obj['__handlerList'];
        for (var __doo__i = 0; __doo__i < handlers.length; __doo__i++) {
            ____hh = Doo.Utils.eval(scripts, handlers[__doo__i]);
            events.addHandler(name, ____hh);
        }
    },

    SetFuns: function (obj, functions) {
        for (var name in functions) {
            obj[name] = Doo.Delegate(functions[name], obj);
        }
    },

    _createDomToAttach: function (id) {
        var d = this['__d'];
        if (!d) {
            d = document.createElement("div");
            document.body.insertBefore(d, document.body.firstChild);
            this['__d'] = d;
        }
        var i;
        try {
            i = document.createElement("<div id='" + id + "'>");
        } catch (e) {
            i = document.createElement("div");
            i.id = id;
        }

        d.appendChild(i);
        return i;
    },

    InitObj: function (name, fields, events, functions, typename, init, id, parentname) {
        var obj, type;
        if (typename && typename != 0) {
            try {
                type = Type.parse(typename);
            }
            catch (e) {
                throw new Error(typename + "类型未能加载，检查脚本是否引用");
            }
            if (!type.inheritsFrom(Doo.ControlBase)) {
                throw new Error(typename + "类型没有继承Doo.ControlBase");
            }
        }
        else {
            type = Doo.ControlBase;
        }
        obj = $create(type, null, null, null, this._createDomToAttach(name));
        if (fields != null) {
            for (var n in fields) {
                obj[n] = fields[n];
            }
        }

        obj['__id'] = name;
        if (id) {
            obj.ctlid = id;
            obj.scriptsid = parentname;
            Doo.Scripts.add_init(function () { window[parentname].addChild(obj); });
        }
        if (events != null) {
            obj['__handlerList'] = new Sys.EventHandlerList();
            this.SetEvents(obj, events);
        }
        if (functions) this.SetFuns(obj, functions);
        if (init.length > 0) {
            Doo.Scripts.add_init(obj[init]);
        }

        window[name] = obj;
    },

    eventinits: new Array(),

    load_handler: function () { Doo.Scripts.init_complete(); },
    inits: new Array(),
    add_init: function (handler) {
        this.inits.push(handler);
    },
    init_complete: function () {
        //事件初始化

        if (this.eventinits) {
            for (var ei = 0; ei < this.eventinits.length; ei++) {
                this.eventinits[ei]();
            }
            this.eventinits = null;
        }

        for (var ii = 0; ii < this.inits.length; ii++) {
            this.inits[ii]();
        }
        this.inits.length = 0;
    }
}
Sys.Application.add_load(Doo.Scripts.load_handler); //在所有init后执行

Doo.Caching = {
    DataVersionManager:
    {
        init: function () {
            //在页面初始化时执行，对pageversion进行处理
            if (!window['pagever']) return;
            //将pagever加入到缓存中
            var pv = window['pagever'];
            for (var n in pv) {
                var ov = localStorage.getItem(n);
                if (pv[n] < ov) localStorage.setItem(n, pv[n]);
            };
            this.versions = pv;
        },
        versions: null,
        refresh: function () {//刷新
            var vs = this.versions;
            if (!vs) return;
            for (var n in vs) {
                vs[n] = localStorage.getItem(n);
            };
            if (frameElement && frameElement.window && frameElement.window.Doo) {
                frameElement.window.Doo.Caching.DataVersionManager.refresh();
            }
        },
        get_version: function (k) {
            if (this.versions) {
                return this.versions[k];
            }
        }
    }
}
Doo.Caching.DataVersionManager.init(); //初始化版本数据库

Doo.Behavior = {
    "hide": function (elem) {
        elem.style.display = "none";
    },
    "watermark": (function () {
        ///<summary>水印文本框</summary>
        var watermark_css = "watermark",
    watermark_focus = function () {
        var a = this;
        if (a['watering']) {
            a.value = '';
            Sys.UI.DomElement.removeCssClass(a, watermark_css);
        }
    },
        watermark_blur = function () {
            var a = this;
            if (a.value == '') {
                a['watering'] = true;
                Sys.UI.DomElement.addCssClass(a, watermark_css);
                a.value = a['watertxt'];
            }
            else {
                a['watering'] = false;
            }
        },
        makeWaterMark = function (txtbox, watertxt) {
            if (txtbox['beh_watermark']) return;
            txtbox['beh_watermark'] = true;
            txtbox['watertxt'] = watertxt.watertxt || watertxt; //可能传入一个对象或字符串
            $addHandler(txtbox, "focus", watermark_focus);
            $addHandler(txtbox, "blur", watermark_blur);

            var og = txtbox.get_value;
            txtbox.get_value = function () {
                var v = og ? og(this) : this.value;
                if (this['watering'] == true) return '';
                else return v;
            };

            watermark_blur.call(txtbox);
        };
        return makeWaterMark;
    })()
}

Doo.ControlBase = function (element) {
    Doo.ControlBase.initializeBase(this, [element]);
}

Doo.ControlBase.Items =
{
    length: 0,
    controls: {},
    add: function (control) {
        control.index = this.length;
        this.controls[this.length++] = control;
    },
    remove: function (control) {
        this.controls[control.index] = null;
    },
    get: function (index) {
        return this.controls[index];
    }
}

var $items = Doo.ControlBase.Items;

Doo.ControlBase.prototype = {
    initialize: function () {
        Doo.ControlBase.callBaseMethod(this, 'initialize');

        this['__handlerList'] = new Sys.EventHandlerList();
        Doo.ControlBase.Items.add(this);

        Doo.Scripts.SetEvents(this, this.initevents);
        this.childs = [];
        this.namedchilds = {};
        // 如果有父级，则添加自己
        var so = this.get_scripts();
        if (so && so.addChild) {
            so.addChild(this);
        }

    },
    dispose: function () {
        //Add custom dispose actions here
        Doo.ControlBase.Items.remove(this);
        //处理子控件
        this.clearChilds();
        this._asyncver = -1;

        Doo.ControlBase.callBaseMethod(this, 'dispose');
    },

    _loaded: false,

    load: function () {
        ///<summary>在派生类重写时，处理load的内容。当所在容器中所有控件完成initialize时即触发load</summary>
        if (this.childs && this.childs.length > 0) {
            Array.forEach(this.childs, function (c) { if (c.load) c.load(); });
        }
        this._loaded = true;
    },

    __handlerList: null,

    __validators: null,
    isValid: function () {
        ///<summary>是否已通过验证</summary>
        if (this.__validators instanceof Array) {//如果有验证器
            return false;
        }
        else {//没有验证器就直接返回false
            return true;
        }
    },

    __dataitem: 0,
    set___dataitem: function (v) { this.__dataitem = v; },
    get___dataitem: function () { return this.__dataitem; },

    index: null,

    ctlid: null,

    scriptsid: null, //所依附的脚本对象，将作为其子对象
    __scope: null, //域
    get_scripts: function () {
        ///<returns type="Doo.ControlBase">返回脚本对象<returns>
        var i = this.scriptsid;
        return i == null ? this.__scope : window[i];
    },

    initevents: {},
    set_initevents: function (evts) {
        this.initevents = evts;
    },
    get_initevents: function () {
        return this.initevents;
    },

    call_event: function (name, args) {
        this.get_scripts()[name](this, args);
    },

    //子控件，用数组是因为没有id的用push方法
    childs: null,
    namedchilds: null,

    _childLock: 0,

    isChildsReady: function () {
        return this._childLock == 0;
    },

    beginCreateChilds: function () {
        this._childLock++;
    },

    endCreateChilds: function () {
        this._childLock--;
        if (this._childLock == 0) {
            this.onChildsReady(this);
        }
    },

    findChild: function (ctlid) {
        return this.namedchilds[ctlid];
    },
    addChild: function (ctl) {
        ///<param name="ctl" type="Sys.UI.Control"></param>
        if (ctl == this) {
            throw new Error("循环错误");
        }
        if (ctl.ctlid) {
            this.namedchilds[ctl.ctlid] = ctl;
        }
        var _this = this;
        this.childs.push(ctl);
        this.onChildAdded(ctl);
    },
    clearChilds: function () {
        var cs = this.childs;
        for (var i = 0; i < cs.length; i++) {
            if (cs[i] && cs[i].dispose) cs[i].dispose();
        }

        this.childs.length = 0;
        this.namedchilds = {};
    },

    _asyncver: 0, //同步版本，避免出错

    newAsync: function () {
        ///<summary>创建新同步版本号</summary>
        return ++this._asyncver;
    },

    get_asyncver: function () {
        ///<summary>获取当前同步版本号</summary>

        return this._asyncver;
    },

    checkAsync: function (v) {
        ///<summary>检查同步版本号</summary>
        return !(v != this._asyncver || v < 0);
    },
    tplevents: null, //事件定义
    get_tplevents: function () {
        /// <returns type="Array"></returns> 
        return this.tplevents;
    },
    set_tplevents: function (es) {
        ///<summary>设置模版事件</summary>
        this.tplevents = es;
    },
    init_tplevents: function (es) {
        ///<summary>用字符串形式初始化模版事件集</summary>
        var context = this.get_scripts() || window;

        for (var __doo__i in es) {
            if (es[__doo__i].length) {
                es[__doo__i] = Doo.Utils.eval(context, es[__doo__i]);
            }
        }
        this.tplevents = es;
    },
    set_inittplevents: function (es) {
        this.init_tplevents(es);
    },
    get_inittplevents: function () {
        return null;
    },
    init_tplevent: function (name, evtstr) {
        var s = {};
        s[name] = evtstr;
        this.init_tplevents(s);
    },
    get_tplevent: function (name) {
        if (!this.tplevents) return null;
        return this.tplevents[name];
    },
    set_tplevent: function (name, evt) {
        if (!this.tplevents) this.tplevents = {};
        this.tplevents[name] = evt;
    },

    tpleventargs: null, //事件参数

    trig_tplevent: function (event, argindex, elem) {
        var args = this.tpleventargs[argindex];
        var handler = this.get_tplevent(args[0]);
        if (typeof (handler) == 'string') handler = eval(handler);
        if (!event) event = window.event;
        var evt = event == null ? null : new Sys.UI.DomEvent(event); //如果是a标签的href引发的事件则取不到event值
        handler(this, args, elem, evt);
    },

    getBindData: function (deep) {
        ///<summary>获取绑定数据</summary>
        ///<param name="deep">是否深层获取</param>
        //遍历子控件，目前只遍历当前子控件。
        var oldData = {}, newData = {};
        var nc = this.namedchilds;
        for (var i in nc) {
            var c = nc[i];
            var bindings = c['__bindings'];
            if (!bindings || bindings == {}) continue;
            for (var n in bindings) {
                var d = bindings[n];
                var dp = d[0];
                var getfun = c['get_' + n];
                var nv = getfun ? getfun.call(c) : c[n];
                oldData[dp] = d[1];
                newData[dp] = nv;
            }
        }
        return { olddata: oldData, newdata: newData };
    }
}

Doo.Scripts.SetEvents(Doo.ControlBase.prototype, { "ChildsReady": 0, "ChildAdded": 0 });
Doo.ControlBase.registerClass('Doo.ControlBase', Sys.UI.Control);

Doo._CreatePageControls = function (ctlidArray) {
    ///<summary>由框架调用，创建页面上的控件</summary>
    if (!window.$Page) $Page = $create(Doo.ControlBase, null, null, null, document.body);
    var callback = function (ctl) {
        $Page.addChild(ctl);
    };
    for (var i = 0; i < ctlidArray.length; i++) {
        $ctl(ctlidArray[i], callback, null, null, $Page);
    }
}

Doo.ControlScripts = {};

Doo.ControlTag = {
    ///<summary>标签注册，格式scopename-namespace</summary>
    "doo": ["Doo",
        {
            "listview": "ListView",
            "gridview": "GridView",
            "pager": "Pager",
            "objdatasource": "DataSource.ObjDataSource"
        }]
}

Doo.ControlLoader = {
    scriptLoaded: function (sender, context, _errcount) {
        var controltype = context["type"];
        var type, typeLoaded = 1;
        var checkTypes = context["checkTypes"];
        for (var i = checkTypes.length - 1; i >= 0; i--) {
            var ct = checkTypes[i];
            if (!Type.hasType(ct)) {
                typeLoaded = 0;
                break;
            }
        }
        if (typeLoaded == 1) {
            try {
                type = Type.parse(controltype);
                if (typeof (type) == 'undefined') {
                    typeLoaded = 0;
                }
            }
            catch (e) {
                typeLoaded = 0;
            }
        }

        if (typeLoaded == 0) {
            _errcount = (_errcount || 0) + 1;
            if (_errcount > 20)
                throw new Error(controltype + "类型无法加载");
            else {
                setTimeout(function () { Doo.ControlLoader.scriptLoaded(sender, context, _errcount); }, _errcount * 10);
                return;
            }
        }
        Sys.Debug.trace("类型已加载[脚本加载器]:" + controltype);
        var path = context["url"];
        if (path) {
            var li = path.lastIndexOf('/');
            type.prototype['path'] = path.substring(0, li + 1); //所有这一类型的控件路径均为这个
        }
        Doo.ControlLoader.loadedType[controltype] = 1; //此时该类型才加载完成[成功赋值path]

        //遍历要创建的控件数组
        var cs = Doo.ControlLoader.waitTypeControl[controltype];
        for (var i = 0; i < cs.length; i++) {
            var ctx = cs[i];
            var elem = ctx[0];
            var props = ctx[2] || {};
            var asyncV = ctx[4];
            var asyncSrc = ctx[5];
            if (asyncSrc && !asyncSrc.checkAsync(asyncV)) return; //同步版本号校验失败
            var callback = ctx[3];
            var control = $create(type, props, null, null, elem);
            control['__scope'] = asyncSrc;
            Doo.ControlLoader.controlCreated(elem, control);
            Sys.Debug.trace("控件已加载[脚本加载器]:" + control._element.id);

            if (callback) callback(control, ctx[6]);
        }

        delete Doo.ControlLoader.waitTypeControl[controltype];
    },

    loadedType: {}, //加载类型
    waitTypeControl: {}, //类型加载完成后要创建的控件

    resources: null,
    _path2version: null,
    _initres: function (res, array, path) {
        for (var n in res) {
            var v = res[n];
            if (v instanceof Function) {
                continue;
            }
            else if (v instanceof Array) {
                array[v[0]] = [path + n, v[1]]; //path,version
            }
            else {
                this._initres(v, array, path + n + '/');
            }
        }
    },
    initResources: function (res) {
        ///<summary>注册资源</summary>
        var r = new Array();
        var path = '/';
        this._initres(res, r, path);
        var p2v = [];
        for (var i = 1; i < r.length; i++) {//resIndex从1开始
            p2v[r[i][0]] = r[i][1];
        };
        this._path2version = p2v;
        this.resources = r;
    },
    getResourcePath: function (i) {
        var v = this.resources[i][1];
        return this.resources[i][0] + (v == 0 ? "" : "?t=" + v);
    },
    getVersionByPath: function (p) {
        return this._path2version[p];
    },

    dependServices: {}, //依赖的web服务。格式为resourceIndex:[type,loaded]。loaded为0时为未判断，1时为正在加载，2时为已加载
    initDependServices: function (services, ns) {
        ///<summary>初始化依赖服务</summary>
        ///<param type="Object" name="services">服务，格式为{name:[index,type]}</param>
        var ds = {};
        //附加名字空间和路径
        for (var n in services) {
            var s = services[n];
            //s[0] = this.getResourcePath(s[0]);//还是使用index
            if (ns != '') s[1] = ns + '.' + s[1];
            ds[s[0]] = [s[1]];
        }

        this.dependServices = ds;
    },

    dependFiles: {}, //依赖的文件，格式为 控件类型:依赖资源序号
    initDependFiles: function () {
        ///<summary>初始化依赖文件</summary>
    },

    controlDependServices: {}, //控件依赖的web服务

    initControlDefs: function (defs, ns, tagPrefix) {
        ///<summary>初始化控件定义</summary>
        ///<param type="Array" name="services">控件数组，格式为name:[scriptres,scripttype,dependservices,dependfiles]</param>
        var tags = {};
        for (var n in defs) {
            var def = defs[n];
            //2011.1.18新修改：[resIndex,dependIndex,typename,tagname]，如果后两者为空，则使用n
            var resIndex = def[0], tagname, typename, dependServices;
            if (def.length < 2) {
                tagname = typename = n;
            }
            else if (def[1] instanceof Array) {//新版顺序
                dependServices = def[1];
                tagname = typename = n;
            }
            else {
                dependServices = def[3];
                typename = def[1] || n;
                tagname = def[2] || typename;
            };
            Doo.ControlScripts[ns + '.' + typename] = this.getResourcePath(resIndex);
            //tags[n.toLowerCase()] = tagname;
            var taglni = n.lastIndexOf('.');
            tags[(taglni > 0 ? (n.substr(taglni + 1)) : n).toLowerCase()] = tagname;
            if (dependServices instanceof Array) {
                this.controlDependServices[ns + '.' + typename] = dependServices;
            }
        };
        Doo.ControlTag[tagPrefix.toLowerCase()] = [ns, tags];
    },

    controlCreated: function (elem, control) {
        ///<summary>当控件或Html元素创建完成后调用</summary>
        var getvalue = function (str, elem) {
            ///<summary>转换字符串</summary>
            if (str.length < 2) return str;
            var c0 = str.charAt(0), c1 = str.charAt(1);
            if (c0 == '%') {
                var t = str.substr(1);
                return c1 != '%' ? eval(t) : t;
            }
            else if (c0 == '$') {
                if (c1 == 'i') {//返回子集文本
                    return elem.innerHTML;
                }
                else if (c1 == 'c') {//返回被注释包围的文本
                    var t = elem.innerHTML.trim();
                    if (t.startsWith("<!--") && t.endsWith("-->")) {
                        return t.substring(4, t.length - 3);
                    }
                    throw new Error("没有找到有效的注释区块");
                }
                else if (c1 == 'r' && str.charAt(2) == '-') {//返回引用的控件（同级）[TODO:由于异步加载的特殊性，可能引用到的控件会出现错误，应给予改进，在所有控件创建完成之后再行处理]
                    var scope = control.__scope;
                    return scope == null ? null : scope.findChild(str.substr(2));
                }
                else if (c1 == 'p' && str.charAt(2) == '-') {
                    return Doo.Utils.QueryString.get_para(str.substr(3));
                }
                else if (c1 == "o" || c1 == "a") {//构造对象或数组并返回
                    var isobject = c1 == 'o';
                    var retobj = isobject ? {} : [];
                    var pe = elem.firstChild;
                    while (pe) {
                        if (pe.tagName && Doo.Utils.Dom.getFullTag(pe) == 'doo:prop') {
                            retobj[isobject ? pe.getAttribute("name") : retobj.length] = getvalue(pe.getAttribute("value"), pe);
                        }
                        pe = pe.nextSibling;
                    }
                    return retobj;
                }
            }
            return str;

        }
        var process = function (attrs, elem) {
            var srcattrs = []; //由于原始集合可能会改变，所以需要记录原始集合 2010.11.22
            for (var i = 0; i < attrs.length; i++) {
                var a = attrs[i].name;
                var ti = a.indexOf(':');
                if (ti < 0) continue;
                srcattrs.push([a.substring(0, ti), a.substr(ti + 1), getvalue(attrs[i].value, elem)]);
            }
            for (var i = 0; i < srcattrs.length; i++) {
                var a = srcattrs[i];
                var loader = this.attrLoader[a[0]];
                if (!loader) continue;
                loader.call(this.attrLoader, control, a[1], a[2]); //TODO:处理表达式
            }
        };

        process.call(this, elem.attributes, elem);
        var fs = elem.firstChild;
        while (fs) {
            if (!fs.tagName) {
                fs = fs.nextSibling;
                continue;
            }
            var tn = Doo.Utils.Dom.getFullTag(fs);
            if (tn == "doo:mp") {
                process.call(this, fs.attributes, fs);
            }
            else if (tn == "doo:doex") {
                //doex--调用多个方法
                var methodname = fs.getAttribute("method");
                if (!methodname) throw new Error("未指定方法名");
                var para = [];
                for (var i = 1; i < 10; i++) {//支持直接写9个参数
                    var p = fs.getAttribute("para" + i);
                    if (!p) break;
                    para.push(getvalue(p, fs));
                }

                var pe = fs.firstChild;
                while (pe) {
                    if (pe.tagName && Doo.Utils.Dom.getFullTag(pe) == 'doo:para') {
                        para.push(getvalue(pe.getAttribute("value"), pe));
                    }
                    pe = pe.nextSibling;
                }
                var func = control[methodname];
                if (!func) { throw new Error(methodname + "不是此时创建的控件的一个方法"); }
                func.apply(control, para);
            }
            else if (tn == "doo:bhv") {
                //bh--创建行为
                var type = fs.getAttribute("type");
                if (!type) throw new Error("未指定类型名");
                var para = {};
                var attrs = fs.attributes;
                for (var i = 0; i < attrs.length; i++) {
                    var attit = attrs[i];
                    if (!attit.specified) continue;
                    var attname = attit.nodeName;
                    if (attname == 'type') continue;
                    para[attname] = attit.nodeValue;
                }
                var bhcreator = Doo.Behavior[type];
                bhcreator(control, para);
            }
            else {
                break;
            }
            var ns = fs.nextSibling;
            elem.removeChild(fs);
            fs = ns;
        }
    },

    attrLoader: {
        ///<summary>属性加载器。一个使用加载器的典型属性为set:title="my title"其中set为属性加载器名，title为名字，等号后的内容是要加载的内容。</summary>
        ///调用时，this指向ControlLoader
        ///Doo2.0版不做编译操作，可能在3.0版中引入编译。
        ///传递的参数中value是经过表达式处理后的值
        "set": function (obj, name, value) {
            ///<summary>为对象赋值</summary>
            var setfun = obj['set_' + name];
            if (setfun) {
                setfun.call(obj, value);
            }
            else {
                //针对文本框做特殊处理
                if (name == 'value' && Sys.UI.DomElement.isDomElement(obj) && (value == null || typeof value == undefined)) {
                    value = '';
                };
                obj[name] = value;
            }
        },
        "do": function (obj, name, value) {
            ///<summary>调用对象方法</summary>
            var dofun = obj[name];
            if (typeof (dofun) !== 'function') throw new Error(name + "不是一个有效的方法");
            dofun.call(obj, value);
        },
        "bhv": function (obj, name, value) {
            ///<summary>附加行为，name是行为名字，value是方法</summary>
            var bhv = Doo.Behavior[name];
            bhv(obj, value);
        },
        "evt": function (obj, name, value) {
            ///<summary>为对象事件增加句柄</summary>
            var context = obj.__scope || (obj.get_scripts && obj.get_scripts()) || window,
            handler = context[value] || Doo.Utils.eval(context, value);
            if (!handler) throw new Error(value + "不是一个有效的句柄");

            if (Sys.UI.DomElement.isDomElement(obj)) {
                var delegate = function (evt) {
                    var domevt = new Sys.UI.DomEvent(evt || window.event);
                    handler.call(context, this, domevt); //参数：sender,evt
                };
                $addHandler(obj, name, delegate);
            }
            else {
                var addfun = obj['add_' + name];
                if (typeof (addfun) !== 'function') throw new Error(name + "不是一个有效的事件");
                //value是字符串，此处需要转成handler
                addfun.call(obj, Function.createDelegate(context, handler));
            }
        },
        "nevt": function (obj, name, value) {
            ///<summary>为对象事件增加句柄</summary>
            var context = obj.__scope || (obj.get_scripts && obj.get_scripts()) || window,
            handler = context[value] || Doo.Utils.eval(context, value);
            if (!handler) throw new Error(value + "不是一个有效的句柄");

            if (Sys.UI.DomElement.isDomElement(obj)) {
                var delegate = function (evt) {
                    var domevt = new Sys.UI.DomEvent(evt || window.event);
                    handler.call(context, this, domevt); //参数：sender,evt
                };
                $addHandler(obj, name, delegate);
            }
            else {
                obj[name] = function () {
                    handler.apply(context, arguments);
                };

            };
        },
        "tplevt": function (obj, name, value) {
            ///<summary>为对象模板事件增加句柄</summary>
            //value是字符串，此处需要转成handler
            var context = obj.get_scripts() || window;
            var handler;
            handler = Doo.Utils.eval(context, value);
            if (!handler) throw new Error(value + "不是一个有效的句柄");
            obj.set_tplevent(name, Function.createDelegate(context, handler));
        },
        ///以下只对具有数据项有效

        bindHelper: function (obj, objprop, dataprop, saveoldvalue) {
            ///<summary>绑定帮助器</summary>
            ///<param name="saveoldvalue">是否保存旧值</param>
            var bindings = obj['__bindings'];
            if (!bindings) bindings = obj['__bindings'] = {};
            var oldvalue = undefined;
            if (saveoldvalue) {
                var getfun = obj['get_' + objprop];
                if (getfun) oldvalue = getfun.call(obj);
                else oldvalue = obj[objprop];
            }
            bindings[objprop] = [dataprop, oldvalue];
        },

        'bind': function (obj, name, value) {
            ///<summary>双向绑定</summary>
            this.lbind(obj, name, value);
            this.bindHelper(obj, name, value, true);
        },
        'lbind': function (obj, name, value) {
            ///<summary>单向绑定：数据->属性</summary>
            var dataitem = obj['__dataitem'];
            if (dataitem) {
                this.set(obj, name, dataitem[value]);
            }
        },
        'rbind': function (obj, name, value) {
            ///<summary>单向绑定：属性->数据</summary>
            ///用途：可用于新增数据时，用set赋初始值，bindR将值写入数据
            ///或用于编辑数据时，用set[支持表达式，如空转换，直接用bind会出现空字符串。可用于日期等需要默认值的地方]将数据写入值，用bindR将值写回
            this.bindHelper(obj, name, value, false);
        }
    }
}

$ctl = function (elemorid, callback, controltype, props, asyncSrc, userContext) {
    ///<summary>使用Doo语法从一个Dom元素创建一个控件（延迟创建特性）</summary>
    ///<param name="elemorid" type="String">依附的元素ID或直接传入元素</param>
    ///<param name="callback" type="Function">成功创建元素后的回调，callback(control)</param>
    ///<param name="controltype" type="String">[可选]在代码中指定控件的类型，如果为空，将从Dom的TagName中寻找类型</param>
    ///<param name="props" type="Object">[可选]Json值，将会覆盖元素的ctl\:prop属性中相同属性</param>
    ///<param name="asyncSrc" type="Doo.ControlBase">[可选]同步源，如果过程中同步版本变化，则中断后续操作，将不再创建控件和回调</param>
    ///<remarks>支持多种语法，内置语法有：赋值类：set，绑定类：bind,bindL,bindR，事件类：evt，方法类：do</remarks>
    if (String.isInstanceOfType(elemorid)) {
        elemorid = $get(elemorid);
    }
    Sys.Debug.trace("创建控件" + elemorid.id);
    if (!elemorid) throw new Error("错误的元素在$control调用");
    if (elemorid.control) {
        throw new Error("已经有一个控件了");
    }
    if (!controltype) {
        var tn;
        var so = elemorid.scopeName;
        if (so) { so = so.toLowerCase(); tn = (elemorid.localName || elemorid.nodeName).toLowerCase(); }
        else {//说明浏览器的scopeName没有值，需要从tagName中取
            tn = elemorid.tagName.toLowerCase();
            var si = tn.indexOf(':');
            so = tn.substring(0, si);
            if (!so) throw new Error("没有找到控件类型");
            tn = tn.substr(si + 1);
        }
        var ns = Doo.ControlTag[so];
        if (ns[1][tn]) tn = ns[1][tn];
        controltype = ns[0] + "." + tn;
    }

    //查找并加载依赖项
    var needLoadScriptUrls = []; //需要加载的脚本
    var needCheckTypes = []; //需要检查的类型[以确信真的加载成功了]
    var needWait = false; //需要等待加载
    var scriptUrl;

    //1.加载web服务
    var dependServices = Doo.ControlLoader.controlDependServices[controltype];
    if (dependServices instanceof Array) {
        for (var i = dependServices.length - 1; i >= 0; i--) {//每一个项目分为：
            var serviceIndex = dependServices[i];
            var service = Doo.ControlLoader.dependServices[serviceIndex];
            if (!service || service[1] == 1) continue; //已加载
            else if (service[1] == 0) {
                needWait = true;
                continue;
            }
            var serviceType = service[0];
            if (Type.hasType(serviceType)) continue;
            needLoadScriptUrls.push(Doo.ControlLoader.getResourcePath(serviceIndex));
            needCheckTypes.push(serviceType);
        }
    }

    //2.加载控件脚本
    var typeLoadingStatus = Doo.ControlLoader.loadedType[controltype] || 2; //没有出现的应该假设为已加载
    if (typeLoadingStatus != 0) {//必须的，避免js加载完成，可以解析type，但还没有执行scriptloaded赋值path
        try {
            var type = Type.parse(controltype);
            if (typeof (type) == "undefined") throw new Error();
            typeLoadingStatus = 1;
        }
        catch (e) {
            if (typeLoadingStatus == 1) throw new Error(controltype + "无法加载");
        }
    }
    if (typeLoadingStatus == 2) {
        scriptUrl = Doo.ControlScripts[controltype];
        needLoadScriptUrls.push(scriptUrl);
        needCheckTypes.push(controltype);
        Doo.ControlLoader.loadedType[controltype] = 0; //开始加载某个类型
        Sys.Debug.trace("开始加载类型:" + controltype);
    };
    //Sys.Debug.trace(controltype + "类型加载状态" + typeLoadingStatus);

    if (needLoadScriptUrls.length > 0) {//还有需要加载的脚本
        var v = -1;
        if (asyncSrc) v = asyncSrc.get_asyncver();
        Doo.ControlLoader.waitTypeControl[controltype] = [[elemorid, controltype, props, callback, v, asyncSrc, userContext]];
        Sys.loadScripts(needLoadScriptUrls, Doo.ControlLoader.scriptLoaded, { type: controltype, checkTypes: needCheckTypes, url: scriptUrl });
        return;
    }

    if (typeLoadingStatus == 1) {//已经加载:1.未通过loadScripts加载的 2.通过loadScripts加载且已经执行了Loaded事件的
        var control = $create(type, props, null, null, elemorid);
        control['__scope'] = asyncSrc;
        Doo.ControlLoader.controlCreated(elemorid, control);
        Sys.Debug.trace("控件已加载[直接]:" + elemorid.id);
        if (callback) callback(control, userContext);
        return control;
    }
    else if (typeLoadingStatus == 0) {//正在加载，未执行Loaded事件
        var v = -1;
        if (asyncSrc) v = asyncSrc.get_asyncver();
        Doo.ControlLoader.waitTypeControl[controltype].push([elemorid, controltype, props, callback, v, asyncSrc, userContext]);
    };
}

// Name:        Doo.WebUI.DataSource.base.script.debug.js
// Assembly:    Doo
// Version:     2.1.0.785
// FileVersion: 2.1.0.0
/// <reference name="MicrosoftAjax.js"/>
/// <reference name="Doo.WebUI.core.js"/>
/// <reference name="Doo.WebUI.VersionManager.script.js"/>

Type.registerNamespace("Doo.DataSource");

Doo.Parameter = function () {
    Doo.Parameter.initializeBase(this);
}
Doo.Parameter.prototype =
{
    name: '',
    defaultValue: '',
    get_value: function () { return this.defaultValue; }
}

Doo.Parameter.registerClass('Doo.Parameter', Sys.Component);

Doo.ParameterQueryString = function () { }
Doo.ParameterQueryString.prototype =
{
    queryName: '',
    get_value: function () {
        return window.location.search;
    }
}
Doo.ParameterQueryString.registerClass('Doo.ParameterQueryString', Doo.Parameter);

Doo.ParameterCookie = function () { }
Doo.ParameterCookie.prototype =
{
    cookieName: '',
    get_value: function () { }
}
Doo.ParameterCookie.registerClass('Doo.ParameterCookie', Doo.Parameter);

Doo.ParameterControl = function () { }
Doo.ParameterControl.prototype =
{
    controlid: '',
    propname: 'value',
    get_value: function (scope) {
        var ctl;
        if (scope) {
            ctl = scope.findChild(this.controlid);
        }
        if (!ctl) {
            var elem = $get(this.controlid);
            if (!elem) throw new Error("找不到元素");
            ctl = elem.control || elem;
        }

        //寻找属性
        var propname = this.propname;
        var getmethod = 'get_' + propname;
        if (typeof (ctl[getmethod]) == 'function') {
            return ctl[getmethod]();
        }
        if (propname in ctl) {
            return ctl[propname];
        }

        throw new Error("不存在的属性或字段");
    }
}
Doo.ParameterControl.registerClass('Doo.ParameterControl', Doo.Parameter);

Doo.DataSource.Base = function (element) {
    Doo.DataSource.Base.initializeBase(this, [element]);
}

Doo.DataSource.Base.prototype = {
    initialize: function () {
        Doo.DataSource.Base.callBaseMethod(this, 'initialize');
        // Add custom initialization here
    },
    dispose: function () {
        //Add custom dispose actions here
        Doo.DataSource.Base.callBaseMethod(this, 'dispose');
    },

    /* 缓存相关 */
    enableversion: false,
    versionkey: '',
    get_version: function () {
        return Doo.Caching.DataVersionManager.get_version(this.versionkey);
    },

    /* select方法 */
    select: function (onsucc, onfail, option, userContext) {
        ///<summary>选择接口</summary>
        if (this.onselecting) this.onselecting(this);
    },
    selectsucc: function (result, args) {
        //result:数据，args:select方法的参数

        if (this.onselected) this.onselected(this);

        var onsucc = args.onsucc;
        if (!onsucc) return;
        onsucc(result, args.userContext);
    },
    selectfail: function (err, args) {

        if (this.onselected) this.onselected(this);

        var onfail = args && args.onfail;
        if (!onfail) alert(err.get_message());
        else onfail(err, args.userContext);
    },

    initevents: { selecting: 0, selected: 0 }

}
Doo.DataSource.Base.registerClass('Doo.DataSource.Base', Doo.ControlBase);

Doo.DataSource.Base.prototype.Select = Doo.DataSource.Base.prototype.select;

// Name:        Doo.WebUI.DataView.script.debug.js
// Assembly:    Doo
// Version:     2.1.0.785
// FileVersion: 2.1.0.0
/// <reference name="MicrosoftAjax.js"/>
/// <reference path="/WebUI/core.debug.js" />

//模版绑定技术
Type.registerNamespace("Doo");

Doo.TemplateBinder = function (context) {
    this.context = context;
    this.tpls = {};
    this.cmtpls = {};
    this.__handlerList = new Sys.EventHandlerList();
}

//模板编译器
Doo.TemplateBinder.Compiler =
(function () {
    var throwErr = function (str) {
        throw new Error("错误的表达式：" + str);
    };
    var bindExpC = function (str) {
        ///<summary>编译绑定表达式（语法：[prop][[?obj1:obj2]|[||objempty]][,format]）。传入的是不包含#的字符串</summary>
        ///<param name="str" type="String">绑定表达式，不包含#</param>
        ///<returns type="Array">编译后的数组</returns>
        //1.辨识?和||
        var len = str.length;
        var IIF = str.indexOf('?');
        var OR = str.indexOf('|');
        var FORMAT = str.indexOf(',');
        if (FORMAT < 0) FORMAT = len;
        var data = [null];
        var propEnd = len;
        if (IIF >= 0) {
            //属于IIF的领地
            propEnd = IIF;
            var THEN = str.indexOf(':', IIF + 1);
            if (THEN < 0 || FORMAT < THEN) {
                throwErr('#' + str);
            }
            if (IIF > 0) data[0] = str.substring(0, IIF);
            data.push('?');
            data.push(str.substring(IIF + 1, THEN));
            data.push(str.substring(THEN + 1, FORMAT));
        }
        else if (OR >= 0 && OR < len - 1 && str.charAt(OR + 1) == '|') {
            propEnd = OR;
            if (FORMAT < OR) {
                throwErr('#' + str);
            }
            if (OR > 0) data[0] = str.substring(0, OR);
            data.push('|');
            data.push(str.substring(OR + 2, FORMAT));
        }
        else {
            data[0] = str.substring(0, FORMAT);
            data.push(null);
        }
        if (FORMAT < len - 1) {
            data.push(str.substr(FORMAT + 1));
        };
        if (data[0] && data[0].indexOf('.') > 0) {//可能是多id
            data[0] = [data[0], data[0].split('.')];
        }
        return data;
    };
    var tplExpC = function (str) {
        ///<summary>编译模板表达式，语法[tplid]|[#exp]|[%exp]</summary>
        ///<param name="str" type="String">表达式，提示，此处的数据上下文为其后的表达式</param>
        ///<returns type="Array">编译后的数组</returns>
        var c = str.charAt(0);
        var data = [c];
        if (c == '#') {
            data.push(bindExpC(str.substr(1)));
        }
        else if (c == '%') {
            data.push(str.substr(1));
        }
        else {
            data[0] = null;
            data.push(str);
        }
        return data;
    };
    var replaceStr = function (str) {
        return str.replace(/(\*?{\*?)|(}\*)/g, function (v) { return v.indexOf('{') >= 0 ? "{" : "}"; });
    };

    return function (tpl, binder) {
        ///<summary>编译模板</summary>
        ///<param name="tpl" type="String"></param>
        ///<param name="binder" type="Doo.TemplateBinder"></param>
        var i = 0, cmdtype;
        var cmtpl = new Array();
        var s = 0; //保存已处理的字符串位置
        while (i < tpl.length) {
            var st = tpl.indexOf('{', i);
            if (st < 0) {
                cmtpl.push(replaceStr(tpl.substring(s, tpl.length + 1)));
                break;
            }
            if (st > 0 && tpl.charAt(st - 1) == '*') {
                i = st + 1;
                continue;
            }

            if ((cmdtype = tpl.charAt(st + 1)).match(/[[$#%]/) == null) {
                i = st + 1;
                continue;
            }
            var en = tpl.indexOf('}', st + 1);
            while (tpl.charAt(en + 1) == '*') {
                en = tpl.indexOf('}', en + 2);
            }

            if (st > s) { cmtpl.push(replaceStr(tpl.substring(s, st))); } //加入纯字符串，不包括最后的{
            //分析brace
            var tplid = null;
            var brace = replaceStr(tpl.substring(st + 1, en));

            var cmdi = 0;
            if (cmdtype == '[') {
                cmdi = brace.indexOf(']', 1);
                if (cmdi < 0) throw new Error("错误的模板ID" + brace);
                tplid = brace.substring(1, cmdi);
                tplid = tplExpC(tplid);
                brace = brace.substring(cmdi + 1, brace.length + 1);
                cmdtype = brace.charAt(0);
            }
            var cmdvalue = brace.substring(1, brace.length);
            if (cmdtype == '#') {
                //prop,format
                cmdvalue = bindExpC(cmdvalue);
            }
            else if (cmdtype == '$') {
                //表达式语法：$cmd,xxx,#xxx,>#xxx
                //传递的总是字符串
                var mh = cmdvalue.indexOf(':');
                var ex = new Array(mh < 0 ? cmdvalue : cmdvalue.substring(0, mh)); //ex:[name,value]
                var args = mh < 0 ? null : cmdvalue.substring(mh + 1, cmdvalue.length + 1).split(',');
                var exn = ex[0];
                var expbuilder = (binder && binder.expressBuilder && binder.expressBuilder[exn]) || Doo.TemplateBinder.Compiler.ExpressionBuilder[exn];
                if (!expbuilder) throw new Error("不存在名为" + exn + "的表达式生成器，表达式的正确使用形式为$expname:arg1,arg2,...,argn");
                cmdvalue = expbuilder(args);
            }
            cmtpl.push(new Array(cmdtype, cmdvalue, tplid)); //加入数组形式的命令:[cmdtype,cmdvalue,tplid]

            i = en + 1;
            s = i;
        }
        return cmtpl;
    }
})();

Doo.TemplateBinder.Compiler.ExpressionBuilder =
{
    ///表达式生成器
    ///返回字符串表示生成静态字符串
    ///返回function表示生成时执行该function.
    'event': function (args) {
        ///<summary>事件触发脚本生成器</summary>
        return function (binder) { return Doo.TemplateBinder.Plugin.Event.get_trigscript(binder, args); };
    },
    'pager': function (propname) {
        ///<summary>分页设置表达式</summary>
        return function (binder) { return Doo.TemplateBinder.Plugin.Pager.setpager(binder, propname); };
    },
    'ctl': function (args) {
        ///<summary>控件生成</summary>
        ///<param type="String" name="args">参数，格式为id</param>
        return function (binder) { return Doo.TemplateBinder.Plugin.Control.processcontrol(binder, args[0]); };
    },
    'element': function (args) {
        ///<summary>html元素生成</summary>
        ///<param type="String" name="args">参数，格式为id</param>
        return function (binder) { return Doo.TemplateBinder.Plugin.Control.processcontrol(binder, args[0], true); };
    },
    'tagns': function (args) {
        ///<summary>控件域注册器</summary>
        ///<param type="String" name="args">参数，格式为scope,namespace</param>
        return function () { var ct = Doo.ControlTag; if (!ct[args[0]]) ct[args[0]] = [args[1], {}]; };
    },
    'tagname': function (args) {
        ///<summary>控件名转换器</summary>
        ///<param type="String" name="args">参数，格式为scope,tagname,ctltype</param>
        return function () { var ns = Doo.ControlTag[args[0]]; if (!ns[1][args[1]]) ns[1][args[1]] = args[2]; };
    }
}
Doo.TemplateBinder.Plugin = {};
Doo.TemplateBinder.Plugin.Event = {//事件插件
    processargs: function (binder, args) {//分析参数
        var dataitem = binder.dataItem;
        var newargs = new Array();
        for (var i = 0; i < args.length; i++) {
            if (args[i].charAt(0) != '#') { newargs.push(args[i]); continue; }

            var prop = args[i].substr(1);
            newargs.push(prop ? dataitem[prop] : dataitem);
        }
        return newargs;
    },
    get_trigscript: function (binder, args) {//得到脚本
        var context = binder.context;
        if (!context.tpleventargs) context.tpleventargs = [];
        var argindex = context.tpleventargs.length;
        context.tpleventargs.push(this.processargs(binder, args));
        return String.format('$items.get({0}).trig_tplevent(event,{1},this);', context.index, argindex);
    }
};
Doo.TemplateBinder.Plugin.Pager = {//分页插件
    setpager: function (binder, prop) {
        var recordcount = binder.dataItem[prop];
        var pager = binder.context.get_pager();
        if (!pager) return;
        pager.set_recordcount(recordcount);
        pager.render();
    } //刷新pager
};
Doo.TemplateBinder.Plugin.Control = {//控件生成
    __maxid: 0,
    newid: function () {
        return "__doo__" + this.__maxid++;
    },
    /*delegatea: function (ctl, element) {
    ///<summary>确保domready事件中会调用自己以创建控件</summary>
    ///<param type="Doo.ControlBase" name="ctl"></param>
    var c = ctl['__tplcontrol'];
    if (c instanceof Array) {
    ctl.beginCreateChilds();
    //1.创建
    var v = ctl.newAsync();
    for (var i = 0; i < c.length; i++) {
    var d = c[i];
    var domid = d[0];
    var ctlid = d[1];
    var dataitem = d[2];
    var domelement = $get(domid);
    ctl.beginCreateChilds();

    if (d[3]) {//d[3]---IsElement是否是html元素而不是控件
    domelement.ctlid = ctlid;
    domelement.__dataitem = dataitem;
    Doo.ControlLoader.controlCreated(domelement, domelement);
    ctl.addChild(domelement);
    ctl.endCreateChilds();
    }
    else {
    $ctl(domelement, function (contrl, cid) {
    if (!ctl.checkAsync(v)) return;
    contrl.ctlid = cid;
    ctl.addChild(contrl);
    ctl.endCreateChilds();
    }, null, { __dataitem: dataitem }, ctl, ctlid);
    }
    }

    //2.清理
    ctl['__tplcontrol'].length = 0;

    ctl.endCreateChilds();
    }
    else {
    throw new Error("无效的生成");
    }
    },*/

    _mkctl: function (cs, ctl, iscontextctl) {
        var i = 0, cid = '';

        while (i < cs.length) {
            var c = cs[i];
            if (c.tagName && (cid = c.getAttribute("ctlid"))) {
                var isctl = c.scopeName && c.scopeName.toLowerCase() != 'html';
                isctl = isctl || c.tagName.indexOf(':') >= 0;
                if (!isctl) {//d[3]---IsElement是否是html元素而不是控件
                    c.__scope = ctl;
                    Doo.ControlLoader.controlCreated(c, c);
                    if (iscontextctl) ctl.addChild(c);
                }
                else {
                    $ctl(c, function (contrl, cid) {
                        contrl.ctlid = cid;
                        if (iscontextctl) ctl.addChild(contrl);
                    }, null, {}, ctl, cid);
                }
            };

            if (c.childNodes) arguments.callee(c.childNodes, ctl, iscontextctl);

            i++;
        };
    },

    makectl: function (binder, frag) {
        ///<summary>先执行本函数以创建用ctlid的控件或元素</summary>
        var ctl = binder.context;
        var iscontextctl = ctl.addChild ? true : false;
        //if (iscontextctl && !ctl.checkAsync(binder['__asyncver'])) return; //同步状态失败，可能是已中止加载
        binder.beginLock();

        this._mkctl(frag.childNodes, ctl, iscontextctl);

        binder.endLock();
    },
    delegatea: function (binder, frag) {
        ///<summary>确保domready事件中会调用自己以创建控件</summary>
        ///<param type="Doo.TemplateBinder" name="binder"></param>
        var c = binder['__tplcontrol'];
        var ctl = binder.context;
        var iscontextctl = ctl.addChild ? true : false;

        if (iscontextctl && !ctl.checkAsync(binder['__asyncver'])) return; //同步状态失败，可能是已中止加载
        if (c instanceof Array) {
            //ctl.beginCreateChilds();
            binder.beginLock();
            //1.创建
            var v = iscontextctl && ctl.get_asyncver(); //由于会出现多个区域同时对ctl操作的情况，此处不再设置新同步状态
            for (var i = 0; i < c.length; i++) {
                var d = c[i];
                var domid = d[0];
                var ctlid = d[1];
                var dataitem = d[2];
                var domelement = frag.getElementById ? frag.getElementById(domid) : frag.querySelector("#" + domid);
                //ctl.beginCreateChilds();
                binder.beginLock();

                if (d[3]) {//d[3]---IsElement是否是html元素而不是控件
                    domelement.ctlid = ctlid;
                    domelement.__dataitem = dataitem;
                    domelement.__scope = ctl;
                    Doo.ControlLoader.controlCreated(domelement, domelement);
                    if (iscontextctl) ctl.addChild(domelement);
                    binder.endLock();
                    //ctl.endCreateChilds();
                }
                else {
                    $ctl(domelement, function (contrl, cid) {
                        if (iscontextctl && !ctl.checkAsync(v)) return;
                        contrl.ctlid = cid;
                        if (iscontextctl) ctl.addChild(contrl);
                        //ctl.endCreateChilds();
                        binder.endLock();
                    }, null, { __dataitem: dataitem }, ctl, ctlid);
                }
            }

            //2.清理
            binder['__tplcontrol'].length = 0;
            binder.endLock();
        }
        else {
            throw new Error("无效的生成");
        }
    },
    ensureEventReg: function (binder) {
        ///<summary>确保domready事件中会调用自己以创建控件</summary>
        ///<param type="Doo.DataViewBase" name="context"></param>
        if (binder['__tplcontroleventreg']) return;
        binder['__tplcontroleventreg'] = true;
        binder['__tplcontrol'] = new Array();
        var context = binder.context;
        binder['__asyncver'] = context.get_asyncver ? context.get_asyncver() : 0;
        binder.add_domready(this.delegatea);
    },
    processcontrol: function (binder, id, iselement) {
        ///<summary>处理control表达式，向添加内容</summary>
        ///<param type="Doo.TemplateBinder" name="binder"></param>
        ///<param type="String" name="id"></param>
        ///<param type="Boolean" name="iselement">是否仅是html元素</param>
        var context = binder.context;
        this.ensureEventReg(binder);
        var domid = this.newid();
        binder['__tplcontrol'].push([domid, id, binder.dataItem, iselement]);
        return domid;
    }
};

Doo.TemplateBinder.LoadTpl = {
    load: function (url, TemplateBinder) {
        TemplateBinder.istplready = false;
        TemplateBinder.loadingurl = url;
        var ishtml = url.endsWith("#htm");


        var request = new Sys.Net.WebRequest();
        request.set_url(ishtml ? (url.substring(0, url.length - 4)) : url);
        request.add_completed(Doo.TemplateBinder.LoadTpl._loadok);
        request.set_userContext({ loadingurl: url, binder: TemplateBinder, ishtml: ishtml });
        request.invoke();
    },
    _loadok: function (response) {
        ///<summary></summary>
        var context = response.get_webRequest().get_userContext();
        var tplbinder = context.binder;
        if (context.loadingurl != tplbinder.loadingurl) return; //目标载入页已更改，则放弃

        tplbinder.cmtpls = [];

        if (!context.ishtml) {
            var xml = response.get_xml();
            if (xml == null) {
                tplbinder.context.set_html(Doo.Resource.TemplateLoadFail);
                return;
            }

            var tpls = xml.getElementsByTagName("template");

            for (var i = 0; i < tpls.length; i++) {
                var id = tpls[i].getAttribute('id');
                var tpl = tpls[i].text;
                tplbinder.tpls[id] = tpl;
            }
        }
        else {
            tplbinder.tpls['root'] = response.get_responseData();
        };
        tplbinder.istplready = true;
        if (tplbinder.ontplready != null) {
            tplbinder.ontplready();
        }
    }
};

Doo.TemplateBinder.prototype = {
    context: null, ///上下文环境
    istplready: true, ///模板是否可用
    tpls: null, ///没有编译的模板
    cmtpls: null, ///已经编译的模板
    roottplid: 'root', ///根模板ID
    ontplready: null,

    set_tpl: function (id, tpl) {
        this.tpls[id] = tpl;
        this.cmtpls[id] = null;
    },
    set_tpls: function (tpls) {
        this.tpls = tpls;
        this.cmtpls = {};
    },

    expressBuilder: {},

    get_cmtpl: function (tplid) {
        var cmtpl = this.cmtpls[tplid];
        if (cmtpl) return cmtpl;

        var tpl = this.tpls[tplid];
        if (!tpl) throw new Error("Error TemplateID:" + tplid);

        this.cmtpls[tplid] = Doo.TemplateBinder.Compiler(tpl, this);

        return this.cmtpls[tplid];
    },

    _bindtrack: null, ///绑定深度

    dataItem: null, //当前数据项

    _bindcmd: (function () {

        var bindExpR = function (dataitem, cmd) {
            var d = cmd[0];
            var result = (d == null || d.length == 0) ? dataitem : ((d instanceof Array) ? (function (a, b) {
                if (a[0] in b) return b[a[0]];
                for (var i = 0; i < a[1].length; i++) b = b[a[1][i]];
                return b;
            })(d, dataitem) : dataitem[d]);
            var i = 2;
            var t = cmd[1];
            if (t == '?') {
                result = Doo.TemplateBinder.Executor.QuickFunc.isempty(result) ? cmd[3] : cmd[2];
                i += 2;
            }
            else if (t == '|') {
                if (Doo.TemplateBinder.Executor.QuickFunc.isempty(result)) result = cmd[2];
                i++;
            }
            if (cmd[i]) {//有格式字符串
                result = String.format("{0:" + cmd[i] + "}", result);
            }
            return result;
        };

        return function (type, cmd, tplid, builder) {
            ///<summary>处理命令</summary>
            var result = null;
            var DataItem = this.dataItem;
            if (DataItem == null) return;

            if (type == '%') {
                result = Doo.TemplateBinder.Executor.Eval.call(this, cmd, DataItem);
            }
            else if (type == '#') {//目前分有无格式化字符串
                result = bindExpR(DataItem, cmd);
            }
            else if (type == '$') {
                if (typeof (cmd) == 'function') {
                    result = cmd(this);
                }
                else {
                    result = cmd;
                }
            }

            if (!tplid) {
                builder.push(result);
                return;
            }
            var c = tplid[0];
            if (c == null) {
                tplid = tplid[1];
            }
            else if (c == '%')//%
                tplid = Doo.TemplateBinder.Executor.Eval.call(this, tplid[1], DataItem);
            else if (c == '#') {//#
                tplid = bindExpR(result, tplid[1]);
            }

            if (!tplid) return;
            var cmtpl = this.get_cmtpl(tplid);
            return this._bindtpl(result, cmtpl, builder);
        }
    })(),

    _bindfunc: function (index, data, cmtpl, builder) {
        this._bindtrack.push(index);
        this.dataItem = data;
        for (var i = 0; i < cmtpl.length; i++) {
            var cmd = cmtpl[i];
            if (typeof (cmd) == 'string') builder.push(cmd);
            else {
                this._bindcmd(cmd[0], cmd[1], cmd[2], builder);
            }
        };
        this._bindtrack.pop();
    },

    _bindtpl: function (data, cmtpl, builder) {
        ///<summary>使用生成器和模板绑定数据</summary>
        var olddataitem = this.dataItem;

        if (data && Array.isInstanceOfType(data)) {
            for (var di = 0; di < data.length; di++) {
                this._bindfunc(di, data[di], cmtpl, builder);
            }
        }
        else {
            this._bindfunc(0, data, cmtpl, builder);
        }
        //绑定完毕
        this.dataItem = olddataitem; //恢复dataItem
        return '';
    },

    __handlerList: null,

    _lock: 0,
    beginLock: function () {
        this._lock++;
    },
    endLock: function () {
        this._lock--;
        if (this._lock == 0) {
            this.onready(this);
        }
    },

    bind: function (data, tplid) {
        ///<summary>使用模板绑定数据</summary>
        if (!tplid) tplid = this.roottplid;
        var builder = new Array();
        this._bindtrack = new Doo.TemplateBinder.Executor.Track();
        this._bindtpl(data, this.get_cmtpl(tplid), builder);
        this._bindtrack = null;
        return builder.join('');
    },

    bindEx: function (data, tplid, callback) {
        ///<summary>使用模版绑定数据，并生成控件。使用callback接收创建好的文档碎片</summary>
        var html = this.bind(data, tplid);
        var delegate = Function.createDelegate(this, function (frag) {

            Doo.TemplateBinder.Plugin.Control.makectl(this, frag);

            var ready = function (binder) {
                binder.remove_ready(ready);
                callback(frag);
            };
            this.add_ready(ready);
            this.beginLock();
            this.ondomready(this, frag);
            this.endLock();
        });
        this['__tplcontroleventreg'] = false;
        Doo.Utils.Dom.createElement(html, delegate);
    }
}

Doo.Scripts.SetEvents(Doo.TemplateBinder.prototype, { "domready": 0, "ready": 0 });

Doo.TemplateBinder.Bind = function (context, cmtpls, data) {
    ///<summary>使用模版技术绑定数据，传递已编译的模版</summary>
    var tplBinder = new Doo.TemplateBinder(context);
    tplBinder.cmtpls = cmtpls;
    return tplBinder.bind(data);
}
Doo.TemplateBinder.BindEx = function (context, cmtpls, data, callback) {
    ///<summary>使用模版技术绑定数据，传递已编译的模版</summary>
    var tplBinder = new Doo.TemplateBinder(context);
    tplBinder.cmtpls = cmtpls;
    return tplBinder.bindEx(data, null, callback);
}
Doo.TemplateBinder.Executor = //执行器
{
QuickFunc: {
    ///<summary>绑定时可用的方法</summary>
    isempty: function (obj) {
        if (obj == null) return true;
        if (obj == '') return true;
        if (obj.length && obj.length == 0) return true;
        return false;
    }
},
CachedCmd: {},
Eval: function (cmd, dataitem) {
    ///<summary>用于在特定环境下执行语句</summary>
    //此处用with的原因是为了AjaxMin不会压缩此处的变量
    with (Doo.TemplateBinder.Executor.QuickFunc) {
        var DataItem = d$ = dataitem;
        return eval(cmd);
    }
}
}

Doo.TemplateBinder.Executor.Track = function () { };
Doo.TemplateBinder.Executor.Track.prototype =
{
    ///堆栈
    _track: new Array(),
    push: function (v) { this._track.push(v); },
    pop: function () { this._track.pop(); },
    toString: function () { return this._track.join(','); }
}

Doo.TemplateBinder.registerClass("Doo.TemplateBinder");

$binder = (function () {
    var cmtpls = {};
    var binder = new Doo.TemplateBinder(window);
    var ensurefunc = function (tpl) {
        var cmtpl;
        if (!(tpl in cmtpls)) {
            cmtpl = Doo.TemplateBinder.Compiler(tpl);
            cmtpls[tpl] = cmtpl;
        }
        else {
            cmtpl = cmtpls[tpl];
        };
        binder.cmtpls['root'] = cmtpl;

    };
    var bindfunc = function (tpl, data) {
        ensurefunc(tpl);
        return binder.bind(data);
    };
    var bindexfunc = function (tpl, data, callback, context) {
        ensurefunc(tpl);
        binder.context = context || $Page;
        binder.bindEx(data, null, callback);
    };
    return { _binder: binder, bind: bindfunc, bindEx: bindexfunc };
})();

Doo.DataViewBase = function (element) {
    this._templatebinder = new Doo.TemplateBinder(this);

    Doo.DataViewBase.initializeBase(this, [element]);
}

Doo.DataViewBase.prototype =
{
    _templatebinder: null,

    /* 编译模版 */
    get_cmtpl: function (name) {
        /// <returns type="Array"></returns> 
        return this._templatebinder.get_cmtpl(name);
    },


    /* 设置内部HTML */
    set_html: function (html) {
        this.get_element().innerHTML = html;
    },
    set_htmlAsync: function (html, callback) {
        Doo.Utils.Dom.setHtmlAsync(this.get_element(), html, callback);
    },
    /* 关联的分页控件 */
    pagerid: null,
    pager: null,
    _pagerHandler: null,
    get_pager: function () {
        /// <returns type="Doo.Pager"></returns> 
        return this.pager;
    },
    set_pager: function (pager) {
        var lv = this;
        if (lv.pager == pager) return;
        if (lv.pager && lv._pagerHandler) { pager.remove_pageindexchange(lv._pagerHandler); };
        lv.pager = pager;
        var changed = function (pager) { lv.pagerchanging(pager); };
        pager.add_pageindexchange(changed);
        lv._pagerHandler = changed;
    },
    pagerchanging: function (pager) {//当分页改变时
        this._fetchdata();
    },

    /* 关联的数据源 */
    datasourceid: null,
    datasource: null,
    set_datasource: function (v) { this.datasource = v; },
    get_datasource: function () {
        /// <returns type="Doo.DataSource.Base"></returns> 
        return this.datasource;
    },

    _fetchdata: function () {

        var args = {};
        var pager = this.get_pager();
        if (pager != null) {
            args.rowstart = pager.get_rowstart();
            args.rowcount = pager.get_rowcount();
        }

        this.ondatafetching(this, args);

        if (this.datasource == null) return;
        var onsucc = function (result, userContext) { userContext.lv.databind(result); };
        this.datasource.Select(onsucc, function (err) { alert(err.get_message()); }, { args: args }, { lv: this });
    },

    initialize: function () {
        Doo.DataViewBase.callBaseMethod(this, 'initialize');

        var ts = this;
        this.load_handler = function () { ts.load(); }
        Sys.Application.add_load(this.load_handler);
    },

    autobind: true,
    set_autobind: function (v) {
        this.autobind = ((v == "true")
        || v == "TRUE"
        || v) ? true : false;
    },
    get_autobind: function () {
        return this.autobind;
    },

    load_handler: null,
    onload: null, //由框架赋值
    load: function () {
        if (this.load_handler) {
            Sys.Application.remove_load(this.load_handler);
            this.load_handler = null;
        }

        this.ensurebind();

        if (this.onload) this.onload(this, null);

        if (this.datasource && this.autobind) {
            //如果有数据源，则开始获取数据
            this._fetchdata();
        }
    },

    ensurebind: function () {
        ///<summary>确定绑定环境</summary>
        var s = this.get_scripts();
        var hc = s && s.findChild;

        if (this.datasourceid && !this.datasource) {
            this.datasource = (hc && s.findChild(this.datasourceid)) || $get(this.datasourceid).control;
        }

        //select..
        if (this.pagerid && !this.pager) {
            this.pager = (hc && s.findChild(this.pagerid)) || $get(this.pagerid).control;
            var lv = this;
            var changed = function (pager) { lv.pagerchanging(pager); };
            this.pager.add_pageindexchange(changed);
            this._pagerHandler = changed;
        }
    },

    _bindeddata: null,

    databind: function (data) {
        ///<summary>数据绑定，如果没有传入就使用数据源</summary>
        if (arguments.length < 1) {
            if (!this.datasource || (!this.pager && this.pagerid)) this.ensurebind();
            if (!this.datasource) return; //没有数据源就直接返回
            this._fetchdata();
        }

        this['__bindings'] = null; //重置绑定字段
        this.clearChilds(); //清除所有的子控件

        var bindingArgs = { data: data };
        this.ondatabinding(bindingArgs);
        data = bindingArgs.data;

        var v = this.newAsync();
        this._templatebinder.bindEx(data, null, Function.createDelegate(this, function (frag) {
            if (!this.checkAsync(v)) return; //未通过同步检查
            this._bindeddata = data;
            var e = this.get_element();
            e.innerHTML = "";
            e.appendChild(frag);
            this.ondomready(this, e);
            this.ondatabound(this, data);
        })
            );
    }
}

//datafetching开始获取数据
//databinding数据已获取，准备绑定数据
//databound数据已绑定，且Dom树及控件已生成或已在异步生成中。可以结合isChildsReady和ChildsReady事件在需要子控件的情况
//domready数据绑定，Dom树已生成，但树上控件还未生成
Doo.Scripts.SetEvents(Doo.DataViewBase.prototype, ["datafetching", "databinding", "databound", "domready"]);

Doo.DataViewBase.registerClass('Doo.DataViewBase', Doo.ControlBase);
// Name:        Doo.WebUI.DataSource.ObjDataSource.script.debug.js
// Assembly:    Doo
// Version:     2.1.0.785
// FileVersion: 2.1.0.0
/// <reference name="MicrosoftAjax.js"/>
/// <reference name="Doo.WebUI.core.js"/>
/// <reference name="Doo.WebUI.DataSource.base.script.js"/>

Type.registerNamespace("Doo.DataSource");

Doo.DataSource.ObjDataSource = function (element) {
    Doo.DataSource.ObjDataSource.initializeBase(this, [element]);
}

Doo.DataSource.ObjDataSource.prototype = {
    initialize: function () {
        if (!this.selectargs) this.selectargs = [];
        Doo.DataSource.ObjDataSource.callBaseMethod(this, 'initialize');
        // Add custom initialization here
    },
    dispose: function () {
        //Add custom dispose actions here
        Doo.DataSource.ObjDataSource.callBaseMethod(this, 'dispose');
    },
    alias: false,
    set_alias: function (value) { this.alias = value; window[this.alias] = this; },
    get_alias: function () { return this.alias; },
    objname: false,
    set_objname: function (value) { this.objname = value; },
    get_objname: function () { return this.objname; },
    selectmethod: false, //获取数据的方法
    set_selectmethod: function (value) { this.selectmethod = value; },
    get_selectmethod: function () { return this.selectmethod; },
    selectargs: null,
    set_selectargs: function (value) { this.selectargs = value; },
    get_selectargs: function () { return this.selectargs; },
    versionmethod: false, //检查版本的方法，该方法返回一个参数用于附加在selectmethod的参数上。
    set_versionmethod: function (value) { this.versionmethod = value; },
    get_versionmethod: function () { return this.versionmethod; },
    currentversion: null, //当前版本
    lastcheckversiontime: null, //上次检查版本时间

    /* 参数初始化 */
    set_initselectargs: function (args) {
        //传入数组
        this.selectargs = new Array();
        for (var i = 0; i < args.length; i++) {
            var arg = args[i];
            var item = null;
            switch (arg.type) {
                case "c": //cookie
                    item = new Doo.ParameterCookie();
                    item.cookieName = arg.cookieName;
                    break;
                case "q": //query
                    item = new Doo.ParameterQueryString();
                    item.queryName = arg.queryName;
                    break;
                case "e": //element
                    item = new Doo.ParameterControl();
                    item.controlid = arg.controlid;
                    item.propname = arg.propertyName;
                    break;
                case "p": //parameter
                default:
                    item = new Doo.Parameter();
                    break;
            }
            item.name = arg.name;
            item.defaultValue = arg.defaultValue;
            this.selectargs.push(item);
        }
    },
    get_initselectargs: function () { return null; }, //永远返回null

    appendSelectArg: function (name, defaultValue, typeName, custom1, custom2) {
        var args = this.get_selectargs();
        if (name in args) {
            throw new Error("已经存在的参数：" + name);
        }
        var type = Doo["Parameter" + (typeName || "")];
        if (!type) throw new Error("错误的类型：" + typeName);
        var item = new type();
        item.name = name;
        item.defaultValue = defaultValue;
        switch (typeName) {
            case "Cookie":
                item.cookieName = custom1;
                break;
            case "QueryString":
                item.queryName = custom1;
                break;
            case "Control":
                item.controlid = custom1;
                item.propname = custom2;
                break;
        }
        args.push(item);
    },

    /* 中途修改参数 */
    set_selectarg: function (name, value) {
        var args = this.get_selectargs();
        for (var i = 0; i < args.length; i++) {
            if (args[i].name == name) {
                args[i].defaultValue = value;
                return;
            }
        };
        throw new Error("不存在的参数");
    },

    /* select方法 */
    select: function (onsucc, onfail, option, userContext) {
        ///<summary>从web服务读取</summary>

        Doo.DataSource.ObjDataSource.callBaseMethod(this, 'select');

        if (option == null) option = null;
        var args = option ? option.args ? option.args : {} : {};
        var scope = this.get_scripts();
        for (var i = 0; i < this.selectargs.length; i++) {
            var arg = this.selectargs[i];
            if (arg.name in args) continue;
            args[arg.name] = arg.get_value(scope);
        }

        var selectmethod = eval(this.objname + "." + this.selectmethod);
        if (this.enableversion) { args.version = this.get_version(); };
        selectmethod(args, this.selectsucc, this.selectfail, { onsucc: onsucc, onfail: onfail, option: option, userContext: userContext, ods: this });
    },

    /* insert,update */
    insertmethod: '',

    insert: function (obj, option) {
        //插入

    },

    updatemethod: '',
    update: function (obj, option) {
        ///<summary>从web服务更新，updatemethod传递的参数有updateargs,updateobj</summary>
        var updatemethod = eval(this.objname + "." + this.selectmethod);
    },

    empty: null

}

Doo.DataSource.ObjDataSource.registerClass('Doo.DataSource.ObjDataSource', Doo.DataSource.Base);

Doo.DataSource.ObjDataSource.prototype.Select = Doo.DataSource.ObjDataSource.prototype.select;

// Name:        Doo.WebUI.DataView.ListView.script.debug.js
// Assembly:    Doo
// Version:     2.1.0.785
// FileVersion: 2.1.0.0
/// <reference name="MicrosoftAjax.js"/>
/// <reference name="Doo.Pager.script.js"/>
/// <reference name="Doo.DataSource.base.script.js"/>

Type.registerNamespace("Doo");

Doo.ListView = function (element) {
    this._templatebinder = new Doo.TemplateBinder(this);

    Doo.ListView.initializeBase(this, [element]);
}

Doo.ListView.prototype = {
    initialize: function () {
        Doo.ListView.callBaseMethod(this, 'initialize');

        //加载模板
        if (this.tplurl != null) {
            Doo.TemplateBinder.LoadTpl.load(this.tplurl, this._templatebinder);
        }
    },

    dispose: function () {
        //Add custom dispose actions here
        Doo.ListView.callBaseMethod(this, 'dispose');
    },

    /* 模版 */
    tplurl: null,
    get_tplurl: function () { return this.tplurl; },
    set_tplurl: function (v) {
        if (this.tplurl == v) return;
        this.tplurl = v;
        if (v) Doo.TemplateBinder.LoadTpl.load(v, this._templatebinder);
    },

    set_roottplid: function (id) { this._templatebinder.roottplid = id; },
    get_roottplid: function () { return this._templatebinder.roottplid; },
    set_tpls: function (value) { this._templatebinder.tpls = value; },
    get_tpls: function (value) { return this._templatebinder.tpls; },
    set_tpl: function (name, value) { this._templatebinder.set_tpl(name, value); },

    /* [重载]数据绑定 */
    databind: function (result) {//test
        //判断模板是否读取完成
        var binder = this._templatebinder;
        if (binder.istplready == false) {
            //还在读取中，则继续等待
            var ts = this;
            binder.ontplready = function () { ts.databind(result); };
            return;
        }
        else {//所有条件都已准备好，可以进行绑定操作
            Doo.ListView.callBaseMethod(this, 'databind', [result]);
        }
    },
    _bindtrack: null, //绑定时用
    _items: null, //绑定时用，存储每个item
    get_item: function (i) { return this._items[i]; },
    add_item: function (item) { this._items.push(item); this._currentitem = item; },
    clear_items: function () { this._items = new Array(); },
    _currentitem: null
}

Doo.ListView.registerClass('Doo.ListView', Doo.DataViewBase);

Doo.ListView.ViewItem = function (view) { this.ListView = view; }
Doo.ListView.ViewItem.prototype =
{
    ListView: null,
    _items: new Array(),
    get_item: function (i) { return this._items[i]; },
    add_item: function (item) { this._items.push(item); this.ListView._currentitem = item; },
    clear_items: function () { this._items = new Array(); },

    /* 更新 */
    onupdating: null,
    update: function () {
        var values = {};
        if (this.onupdating) { this.onupdating(this, values); };
        Sys.Debug.trace(values);
    }
}

Doo.ListView.getItem = function (index) {
    var view = this.Items[index];
    if (arguments.length > 1) {
        for (var i = 1; i < arguments.length; i++) {
            view = view.get_item(arguments[i]);
        }
    }
    return view;
}
Type.registerNamespace('Doo');
Doo.Resource = {
    "TemplateLoadFail": "模板加载失败"
};

// Name:        Doo.WebUI.DataView.GridView.script.debug.js
// Assembly:    Doo
// Version:     2.1.0.785
// FileVersion: 2.1.0.0
/// <reference name="MicrosoftAjax.js"/>
/// <reference path="/WebUI/core.debug.js"/>
/// <reference path="/WebUI/DataView/script.debug.js"/>

//GridView用来显示一个表格
//支持显示表头、表尾等
//TODO：
//  1.总是显示表头表尾
//  2.FireFox的MoveRow方法补全

Type.registerNamespace("Doo");

Doo.GridView = function (element) {
    Doo.GridView.initializeBase(this, [element]);
}

Doo.GridView.CreateTpls = function (gridview, fields) {
    ///<summary>从已定义的列中生成模板</summary>
    ///<param name="gridview" type="Doo.GridView">GridView</param>
    ///<param name="fields" type="Array" elementType="Array">预定义的列定义，每个列定义为[headertext,bodytemplate,headerattr,bodycss,footertext]</param>
    var tplHead = new Array();
    var tplRow = new Array();
    var tplCol = new Array();
    var tplFoot = new Array();
    var len = fields == null ? -1 : fields.length;
    if (gridview.get_showRowIndex()) {
        tplHead.push("<th class='rowIndex' style='width:30px;'>{%this.__rowIndex=0?'':''}&nbsp;&nbsp;</th>");
        tplCol.push("<colgroup class='rowIndex'></colgroup>");
        tplRow.push("{%++this.__rowIndex }");
        tplFoot.push("");
    }
    for (var i = 0; i < len; i++) {
        var headerattr = fields[i][2];
        var headertext = fields[i][0];
        var bodycss = fields[i][3];
        var bodytpl = fields[i][1];
        var footer = fields[i][4];
        tplHead.push("<th " + headerattr + " onclick='{$event:__sort}'>");
        tplHead.push(headertext);
        tplHead.push("</th>");
        tplCol.push("<colgroup");
        if (bodycss) tplCol.push(" class='" + bodycss + "'");
        tplCol.push("/>");
        tplRow.push(bodytpl);
        tplFoot.push(footer);
    };
    return {
        'root': '{$pager:RecordCount}<table style="width:100%;border-collapse:collapse;" class="{%this.context.css}">\
        <thead><tr>{[header]#}</tr></thead>' +
        (gridview.get_showfooter() ? '<tfoot>{[footer]#}</tfoot>' : '') +
        '{[colgroup]#}<tbody onmousedown="{$event:__move}">{[#Items?white:emptybody]#}{[row]#Items}</tbody></table>',
        'white': ' ',
        'header': tplHead.join(''),
        'row': '<tr><td>' + tplRow.join('</td><td>') + '</td></tr>',
        'colgroup': tplCol.join(''),
        'footer': '<tr><td>' + tplFoot.join('</td><td>') + '</td></tr>',
        'emptybody': '<tr><td colspan="' + fields.length + '">{[empty]#}</td></tr>'
    };
}

Doo.GridView.prototype = {
    initialize: function () {
        Doo.GridView.callBaseMethod(this, 'initialize');
        // Add custom initialization here
        if (this.columns == null) this.columns = [];
        this._generatetpl();
    },
    dispose: function () {
        //Add custom dispose actions here
        Doo.GridView.callBaseMethod(this, 'dispose');
    },

    _istplgenerated: false,

    _allowSort: true,

    get_allowsort: function () { return this._allowSort; },

    set_allowSort: function (value) {
        this._allowSort = value ? true : false;
    },

    _showfooter: false, //是否显示页脚

    get_showfooter: function (v) {
        return this._showfooter;
    },

    set_showfooter: function (v) {
        this._showfooter = v ? true : false;
        this._istplgenerated = false;
    },

    _showRowIndex: false,

    get_showRowIndex: function () { return this._showRowIndex },

    set_showRowIndex: function (value) {
        if (this._showRowIndex == value) return;
        this._istplgenerated = false;
        this._showRowIndex = value;
    },

    css: '',

    columns: null,
    get_columns: function () {
        ///<summary>获取列定义</summary>
        /// <returns type="Array" elementType="Array">预定义的列定义</returns>
        return this.columns;
    },
    set_columns: function (value) {
        ///<summary>设置列定义</summary>
        /// <param name="value" type="Array" elementType="Array">预定义的列定义，每个列定义为[headertext,bodytemplate,headerattr,bodycss,footertext]</param>
        this.columns = value; this._istplgenerated = false;
    },
    appendColumn: function (headertext, bodytemplate, headerattr, bodycss, footertext) {
        if (!this.columns instanceof Array) {
            this.columns = [];
        }
        this.columns.push([headertext, bodytemplate, headerattr, bodycss, footertext]);
        this._istplgenerated = false;
    },

    get_table: function () {
        ///<summary>获取表格元素</summary>
        return this._element.firstChild;
    },

    get_tbody: function () {
        ///<summary>获取TBody元素</summary>
        return this.get_table().tBodies[0];
    },

    /* 样式设置 */
    get_columnstyle: function (index) {
        ///<summary>获取第index列的样式以供设置</summary>
        ///<param name="index" type="Number">从0开始的序号</param>
        var cols = this.get_tbody().getElementsByTagName("col");
        return cols[index].style;
    },

    emptytpl: '没有数据',

    _generatetpl: function () {
        ///<summary>生成模版</summary>
        var tpls = Doo.GridView.CreateTpls(this, this.columns);
        tpls.empty = this.emptytpl;
        this._templatebinder.set_tpls(tpls);
        this.set_tplevent("__sort", this.sortHandler);
        this.set_tplevent("__move", this.moveHandler);
        this._istplgenerated = true;
    },

    resetRowIndex: function (tbody, start, end) {
        var rows = tbody.rows;
        for (var i = start; i <= end; i++) {
            rows[i].cells[0].innerHTML = i + 1;
        }
    },

    sortHandler: function (sender, args, elem, evt) {
        ///<summary>排序事件处理委托</summary>
        ///<param name="sender" type="Doo.GridView">GridView</param>
        if (!sender._allowSort) return; //elem为th，排序方法就是将tbody中的row重新排序
        var desc = elem['sortdesc'] == true;
        elem['sortdesc'] = !desc;
        var cellIndex = elem.cellIndex;
        var table = elem.offsetParent;
        var tbody = table.tBodies[0];
        var rows = tbody.rows;
        var sortArray = new Array();
        for (var i = 0; i < rows.length; i++) {
            var cell = rows[i].cells[cellIndex];
            var valueForSort = cell.innerText || cell.textContent;
            var numberValue = parseFloat(valueForSort);
            sortArray.push([rows[i], valueForSort, numberValue]);
        }
        sortArray.sort(function (a, b) {
            var result;
            if (!isNaN(a[2]) && !isNaN(b[2])) result = a[2] - b[2];
            else result = a[1] > b[1] ? 1 : a[1] == b[1] ? 0 : -1;
            return desc ? -result : result;
        });
        for (var i = sortArray.length - 1; i >= 0; i--) {
            tbody.moveRow(sortArray[i][0].sectionRowIndex, 0);
        }
        if (sender._showRowIndex) sender.resetRowIndex(tbody, 0, rows.length - 1);
    },

    /* 行移动事件处理 */
    _allowMove: false,
    get_allowMove: function () {
        return this._allowMove;
    },
    set_allowMove: function (value) {
        this._allowMove = value;
    },
    dragContext: (function () {
        var cssPreFix = "Doo_GridView_";
        var all = cssPreFix + "Draging";
        var dragRowCss = cssPreFix + "DragRow";
        var handlerRowCss = cssPreFix + "HandlerRow";
        var sourceHandlerRowCss = cssPreFix + "SourceHandlerRow";
        var tableLayoutFixedCss = cssPreFix + "Fixed";
        var styleSetted = false;
        var ensureStyleSet = function () {
            //保证样式表已经设置
            if (styleSetted) return;
            //0.All
            Doo.Css.addCssRule('.' + all, "position:absolute;width:100%;");
            Doo.Css.addCssRule('.' + all + ' td', "border:none");
            //1.DragRow
            Doo.Css.addCssRule('.' + dragRowCss, "border:dotted 2px black;opacity:0.3;");
            //2.HandlerRow
            Doo.Css.addCssRule('.' + handlerRowCss, "border-top:solid 1px blue");
            //3.sourceHandlerRowCss
            Doo.Css.addCssRule('.' + sourceHandlerRowCss, "border:solid 1px red");
            //4.all
            styleSetted = true;
        }
        return {
            initMY: 0,
            initTop: 0,
            maxHeight: 0,
            sourceRow: null,
            dragRow: null,
            handlerRow: null,
            targetRow: null,
            sourceHandlerRow: null,
            ensure: function (tbody) {
                /// <param name="tbody" DomElement="true"></param>
                if (this.dragRow == null) {
                    var row = this.dragRow = tbody.insertRow(-1);
                    var cell = row.insertCell(-1);
                    var cellSpan = tbody.rows[0].cells.length;
                    cell.cellSpan = cellSpan;
                    cell.innerHTML = "<div>&nbsp;</div>";
                    var hrow = this.handlerRow = tbody.insertRow(-1);
                    var hcell = hrow.insertCell(-1);
                    hcell.cellSpan = cellSpan;
                    hcell.innerHTML = "<div>&nbsp;</div>";
                    var shrow = this.sourceHandlerRow = tbody.insertRow(-1);
                    var shcell = shrow.insertCell(-1);
                    shcell.cellSpan = cellSpan;
                    shcell.innerHTML = "<div>&nbsp;</div>";

                    var table = tbody.parentNode;
                    if (table.style.tableLayout.toLowerCase() == "fixed") {
                        Sys.UI.DomElement.addCssClass(tbody, tableLayoutFixedCss);
                    }

                    //设置样式
                    table.style.position = "relative"; //设置table
                    row.className = all + ' ' + dragRowCss;
                    hrow.className = all + ' ' + handlerRowCss;
                    shrow.className = all + ' ' + sourceHandlerRowCss;
                    ensureStyleSet();
                }
                else {
                    tbody.appendChild(this.dragRow);
                    tbody.appendChild(this.handlerRow);
                    tbody.appendChild(this.sourceHandlerRow);
                }
            },
            clear: function () {
                var tbody = this.dragRow.parentNode;
                tbody.removeChild(this.dragRow);
                tbody.removeChild(this.handlerRow);
                tbody.removeChild(this.sourceHandlerRow);
                this.dragRow = null;
                this.handlerRow = null;
                this.sourceHandlerRow = null;
                //释放资源
            }
        }
    })(),
    moveHandler: function (sender, args, tbody, evt) {
        /// <param name="sender" type="Doo.GridView"></param>
        /// <param name="tbody" domElement="true"></param>
        /// <param name="evt" type="Sys.UI.DomEvent"></param>
        var tgt = evt.target;
        var allowMove = this._allowMove;

        //一直上浮到parentNode为elem
        if (tgt == tbody) return;
        evt.stopPropagation();
        var child = tgt;
        while (tgt && tgt.parentNode != tbody) {
            child = tgt;
            tgt = tgt.parentNode;
            if (!allowMove) {
                if (tgt.getAttribute("moveHandler") == "yes") allowMove = true;
            }
        }
        //找到了
        if (!tgt) return;
        if (!allowMove) {
            //查看列定义是否允许移动
            var i = child.cellIndex;
            if (sender._element.firstChild.tHead.rows[0].cells[i].getAttribute("moveHandler") != "yes") return;
        };
        sender.dragContext.ensure(tbody);
        var top = tgt.offsetTop + 'px';
        sender.dragContext.initMY = evt.clientY;
        sender.dragContext.initTop = tgt.offsetTop;
        sender.dragContext.sourceRow = tgt;
        sender.dragContext.targetRow = tgt;
        sender.dragContext.maxHeight = tbody.offsetHeight;
        sender.dragContext.dragRow.style.top = top;
        sender.dragContext.dragRow.style.height = tgt.offsetHeight + 'px';
        sender.dragContext.dragRow.style.display = '';
        sender.dragContext.handlerRow.style.display = '';
        sender.dragContext.handlerRow.style.top = top;
        sender.dragContext.sourceHandlerRow.style.top = top;
        $addHandler(document, "mousemove", sender.get_movingHandler(), false);
        $addHandler(document, "mouseup", sender.get_endmoveHandler(), false);
    },
    _moving: null,
    get_movingHandler: function () {
        if (this._moving == null) this._moving = Function.createDelegate(this, this.movingHandler);
        return this._moving;
    },
    movingHandler: function (evt) {//正在移动...
        /// <param name="evt" type="Sys.UI.DomEvent"></param>
        var top = this.dragContext.initTop + evt.clientY - this.dragContext.initMY;
        evt.preventDefault();
        evt.stopPropagation();
        //寻找放置的地点
        if (top < 0) return;
        var tbody = this.dragContext.sourceRow.parentNode;
        var targetRow = tbody.rows[0];
        var len = tbody.rows.length - 3; //要减掉3个帮助row
        var i = 1;
        while (i < len && targetRow.offsetTop < top) {
            targetRow = tbody.rows[i++];
        }
        if (i == len && targetRow.offsetTop < top) {
            targetRow = null;
        }
        if (this.dragContext.targetRow != targetRow) {
            //tbody.moveRow(this.dragContext.handlerRow.sectionRowIndex, targetRow.sectionRowIndex);
            this.dragContext.handlerRow.style.top = (targetRow == null ? tbody.offsetHeight + tbody.rows[len].offsetHeight : targetRow.offsetTop) + 'px';
            this.dragContext.targetRow = targetRow;
        }
        this.dragContext.dragRow.style.top = top + 'px';
    },
    _endmove: null,
    get_endmoveHandler: function () {
        if (this._endmove == null) this._endmove = Function.createDelegate(this, this.endMoveHandler);
        return this._endmove;
    },
    _moveRow: function (section, indexFrom, indexTo) {
        ///<summary>移动行，用于修复bug，避免被移动到下一个section</summary>
        var l = section.rows.length - 1;
        if (indexTo < l) {
            section.moveRow(indexFrom, indexTo);
        }
        else {
            var row = section.rows[indexFrom];
            section.moveRow(indexFrom, indexTo - 1);
            section.moveRow(indexTo, indexTo - 1);
        }
    },
    endMoveHandler: function (evt) {//结束移动事件
        /// <param name="evt" type="Sys.UI.DomEvent"></param>
        $removeHandler(document, "mousemove", this.get_movingHandler());
        $removeHandler(document, "mouseup", this.get_endmoveHandler());
        this.dragContext.clear();
        var tbody = this.dragContext.sourceRow.parentNode;
        var targetRow = this.dragContext.targetRow;
        var targetIndex = targetRow == null ? tbody.rows.length : targetRow.sectionRowIndex;
        var oldIndex = this.dragContext.sourceRow.sectionRowIndex;
        if (targetIndex > oldIndex) targetIndex--;
        if (targetIndex == oldIndex) return; //目标为本行，即可不移动
        //oldIndex为本行，targetIndex为将要移动到的行
        var args = new Doo.GridViewRowMovingEventArgs(tbody, this.dragContext.sourceRow, targetIndex);
        this.onrowmoving(this, args);
        if (args.cancer == true) {

        }
        else {
            this._moveRow(tbody, oldIndex, targetIndex);
            args = new Doo.GridViewRowMovedEventArgs(tbody, this.dragContext.sourceRow, oldIndex, targetIndex);
            this.onrowmoved(this, args);
            if (this._showRowIndex) {
                if (oldIndex > targetIndex)
                    this.resetRowIndex(tbody, targetIndex, oldIndex);
                else//targetIndex>oldIndex时
                    this.resetRowIndex(tbody, oldIndex, targetIndex);
            }
        }
    },

    //[已重载]
    databind: function (data) {
        if (this._istplgenerated == false) this._generatetpl();
        Doo.GridView.callBaseMethod(this, 'databind', [data]);
    }
}
Doo.Scripts.SetEvents(Doo.GridView.prototype, { 'rowmoving': 0, 'rowmoved': 0 });
Doo.GridView.registerClass('Doo.GridView', Doo.DataViewBase);

Doo.GridViewRowMovingEventArgs = function (tbody, sourceRow, targetIndex) {
    this.sourceRow = sourceRow;
    this.targetIndex = targetIndex;
    this.tbody = tbody;
};
Doo.GridViewRowMovingEventArgs.prototype = {
    sourceRow: null,
    tbody: null,
    targetIndex: 0,
    cancer: false
};
Doo.GridViewRowMovingEventArgs.registerClass("Doo.GridViewRowMovingEventArgs", Sys.EventArgs);

Doo.GridViewRowMovedEventArgs = function (tbody, sourceRow, oldIndex, targetIndex) {
    this.sourceRow = sourceRow;
    this.targetIndex = targetIndex;
    this.tbody = tbody;
    this.oldIndex = oldIndex;
};
Doo.GridViewRowMovedEventArgs.prototype = {
    sourceRow: null,
    tbody: null,
    oldIndex: 0,
    targetIndex: 0
};
Doo.GridViewRowMovedEventArgs.registerClass("Doo.GridViewRowMovedEventArgs", Sys.EventArgs);

/* 一个排序的例子
var setOrder = function (row, i) { row.cells[1].innerHTML = i; };
var getOrder = function (row) { return parseInt(row.cells[1].innerHTML); };
var oldOrder = getOrder(args.sourceRow);
var min = args.oldIndex, max = args.targetIndex;
if (min > max) { var tmp = min; min = max; max = tmp; }
var i = min;
var tbody = args.tbody;
var maxlen = tbody.rows.length;
var order = 1;
if (i > 0) {
//有前一项，进行计算
var po = getOrder(tbody.rows[i - 1]);
order = po + 1; setOrder(tbody.rows[i], order++);
}
else {
setOrder(tbody.rows[0], order++);
}
while (++i < maxlen) {
//依次计算
var oo = getOrder(tbody.rows[i]);
if (oo > order && i > max) break;
setOrder(tbody.rows[i], order++);
} */
// Name:        Doo.WebUI.Pager.script.debug.js
// Assembly:    Doo
// Version:     2.1.0.785
// FileVersion: 2.1.0.0
/// <reference name="MicrosoftAjax.js"/>

Type.registerNamespace("Doo");

Doo.Pager = function (element) {
    Doo.Pager.initializeBase(this, [element]);
}

Doo.Pager.Items = new Array();

Doo.Pager.prototype = {
    initialize: function () {
        Doo.Pager.callBaseMethod(this, 'initialize');
        this._itemindex = Doo.Pager.Items.length;
        Doo.Pager.Items.push(this);
        // Add custom initialization here

        var pager = this;
        if (this.triggerchangeoninit) {
            Sys.Application.add_load(function () {
                pager.set_pageindex(pager.pageindex);
            });
        }
        this.render();
    },
    dispose: function () {
        //Add custom dispose actions here
        Doo.Pager.callBaseMethod(this, 'dispose');
    },

    _itemindex: 0,

    pageindex: 0,
    set_pageindex: function (value, trig) {
        ///<param name="value" description="0 base" />
        this.pageindex = value;
        if (trig === false) return;
        var phandler = this.get_events().getHandler("pageindexchange");
        if (phandler != null) {
            phandler(this, Sys.EventArgs.Empty);
        }
    },
    get_pageindex: function () { return this.pageindex; },
    pagesize: 99999,
    set_pagesize: function (value) { this.pagesize = value; },
    get_pagesize: function () { return this.pagesize; },
    style: 0,
    set_style: function (value) { this.style = value; },
    get_style: function () { return this.style; },
    recordcount: 0,
    set_recordcount: function (value) { this.recordcount = value; },
    get_recordcount: function () { return this.recordcount; },

    get_pagecount: function () { return this.recordcount == 0 ? 0 : parseInt((this.recordcount - 1) / this.pagesize) + 1; },

    behavior: 0,
    set_behavior: function (value) { this.behavior = value; },
    get_behavior: function () { return this.behavior; },

    alias: null,
    set_alias: function (value) { this.alias = value; },
    get_alias: function () { return this.alias; },

    get_rowstart: function () { return this.pageindex * this.pagesize; },
    get_rowcount: function () { return this.pagesize; },
    get_events: function () {
        if (!this._events) {
            this._events = new Sys.EventHandlerList();
        }
        return this._events;
    },

    add_pageindexchange: function (handler) { this.get_events().addHandler("pageindexchange", handler); },
    remove_pageindexchange: function (handler) { this.get_events().removeHandler("pageindexchange", handler); },

    triggerchangeoninit: false,
    set_triggerchangeoninit: function (value) { this.triggerchangeoninit = value; },
    get_triggerchangeoninit: function () { return this.triggerchangeoninit; },

    render_item: function (index, current, txt) {
        return String.format("<a href='javascript:;' onclick='Doo.Pager.Items[{0}].set_pageindex({1})' class='{3}'>{2}</a>", this._itemindex, index - 1, txt ? txt : index, index == current ? "current" : "");
    },

    render: function () {
        //Render HTML
        var sb = new Sys.StringBuilder();
        while (this.get_pagecount() > 0) {
            var index = this.pageindex + 1;
            var max = this.get_pagecount();

            //Render Prev
            if (this.style == 2 || this.style == 1) {//PrevNext And Both
                if (index > 1) sb.append(this.render_item(index - 1, index, '上一页'));
            };

            //1.Render 1
            sb.append(this.render_item(1, index));

            //2.Render ...
            if (max < 2) break;
            var st = index - 1;
            var en = index + 1;
            if (en > max - 1) {
                st = max - 3;
                en = max - 1;
            }
            if (st < 2) {
                st = 2;
                en = 4;
            }
            if (en > max) en = max;

            if (st > 2) sb.append("...");

            //3.Render Middle
            for (var i = st; i <= en; i++) {
                sb.append(this.render_item(i, index));
            }

            //4.Render ...
            if (en == max) break;
            if (en < max - 1) sb.append("...");

            //5.Render Last
            sb.append(this.render_item(max, index));

            break;
        };
        //Render Next
        if (this.pageindex < this.get_pagecount()) {
            if (this.style == 2 || this.style == 1) {//PrevNext And Both
                if (index < max) sb.append(this.render_item(index + 1, index, '下一页'));
            };
        }

        this._element.innerHTML = sb.toString();
    }
}

Doo.Pager.registerClass('Doo.Pager', Doo.ControlBase);

// Name:        Doo.WebUI.UserControl.script.debug.js
// Assembly:    Doo
// Version:     2.1.0.785
// FileVersion: 2.1.0.0
/// <reference path="/Scripts/MicrosoftAjax/MicrosoftAjax.debug.js"/>
/// <reference path="/WebUI/core.debug.js"/>
/// <reference path="/WebUI/DataView/script.debug.js" />

Doo.UserControlBase = function (element) {
    Doo.UserControlBase.initializeBase(this, [element]);
}

Doo.UserControlBase.HtmlCache = {};

Doo.UserControlBase.prototype = {
    initialize: function () {
        Doo.UserControlBase.callBaseMethod(this, 'initialize');
        if (this.autoShow) {
            var _t = this;
            setTimeout(function () { _t.show(); }, 0);
        }
        else {
            this.domReady(this.get_element());
        }
    },
    path: '',
    htmlfile: '',
    appendversion: 0, //版本号，如大于0则将附加版本号数据
    htmlcontent: 0,
    usePath: true,
    useHtmlFile: true,
    useTemplateBinder: true, //是否使用模版引擎
    autoShow: true,
    getHtml: function (file, callback) {
        ///<summary>远程加载模版，并在加载完成时调用callback</summary>
        /// <param name="callback" type="Function">callback(html)</param>
        var version = this.appendversion;
        if (file.charAt(0) != '/' && this.usePath) {
            file = this.path + file;
            if (version == 0) {
                version = Doo.ControlLoader.getVersionByPath(file) || 0;
            }
        }
        if (version != 0) {
            file += (file.indexOf('?') < 0 ? '?' : '&') + 'v=' + version;
        }
        var callbacks;
        if (file in Doo.UserControlBase.HtmlCache) {
            callbacks = Doo.UserControlBase.HtmlCache[file];
            if (String.isInstanceOfType(callbacks)) {//如果是string，表示是已经加载的内容。如果不是，表示是数组
                this.setHtml(callbacks);
                return;
            }
            callbacks.push(callback);
        }
        else {
            callbacks = [callback];
            Doo.UserControlBase.HtmlCache[file] = callbacks;
            var request = new Sys.Net.WebRequest();
            request.set_url(file);
            request.set_userContext(file);
            request.add_completed(this.getHtml_ok);
            request.invoke();
        }
    },
    getHtml_ok: function (response) {
        /// <param name="result" type="Sys.Net.WebRequestExecutor">根元素</param>
        var file = response.get_webRequest().get_userContext();
        var html = response.get_responseData();
        var callbacks = Doo.UserControlBase.HtmlCache[file];
        Doo.UserControlBase.HtmlCache[file] = html;
        for (var i = 0; i < callbacks.length; i++) {
            callbacks[i](html);
        }
    },
    compiledHtmlTpl: null,
    createBindData: function () {
        ///<summary>在派生类中重载用于获取用来绑定模版的数据</summary>
        return 0;
    },
    setHtml: function (html) {
        var delegate = Function.createDelegate(this,
                function (frag) {
                    var element = this.get_element();
                    element.innerHTML = "";
                    element.appendChild(frag);
                    this.domReady(element);
                    this.onChildsReady();
                });
        if (this.useTemplateBinder) {
            if (this.compiledHtmlTpl == null) { this.compiledHtmlTpl = Doo.TemplateBinder.Compiler(html); };
            Doo.TemplateBinder.BindEx(this, { root: this.compiledHtmlTpl }, this.createBindData(), delegate);
        }
        else {
            Doo.Utils.Dom.createElement(html, delegate);
        }
    },
    dispose: function () {
        //Add custom dispose actions here
        Doo.UserControlBase.callBaseMethod(this, 'dispose');
    },
    _isDomReady: false,
    domReady: function (root) {
        ///<summary>在Dom准备好时触发</summary>
        /// <param name="root" DomElement="true">根元素</param>
        this._isDomReady = true;
        this.ondomready(this, root); //调用系统
        this.onDomReady(root); //调用派生类
        this.onready();
        //为下属控件调用load方法
        if (this.childs && this.childs.length > 0) {
            Array.forEach(this.childs, function (c) { if (c.load) c.load(); });
        }
    },
    onDomReady: function (root) {
        ///<summary>在派生类重写时，在创建的树上实例自己的控件</summary>
    },
    show: function () {
        ///<summary>展示控件</summary>
        if (!this._isDomReady) {
            if (!this.useHtmlFile) {
                if (!this.htmlcontent) {
                    this.domReady(this.get_element());
                }
                else {
                    this.setHtml(this.htmlcontent);
                }
                return;
            }

            if (!this.htmlfile) {
                var _t = this;
                setTimeout(function () { _t.domReady(_t._element); _t.onChildsReady(); }, 0);
                return 0;
            }

            var _this = this;
            var v = this.get_asyncver();
            this.getHtml(this.htmlfile, function (html) {
                if (!_this.checkAsync(v)) return;
                _this.setHtml(html);
            });
        }
    }
}
Doo.Scripts.SetEvents(Doo.UserControlBase.prototype, { ready: 0, "domready": 0 }); //domready小写
Doo.UserControlBase.registerClass('Doo.UserControlBase', Doo.ControlBase);

Doo.Page = function (element) {
    Doo.Page.initializeBase(this, [element]);
}

Doo.Page.prototype = {
    initialize: function () {
        this.useHtmlFile = false;
        this.autoShow = false;

        Doo.Page.callBaseMethod(this, 'initialize');

    },
    createBindData: function () {
        ///<summary>在派生类中重载用于获取用来绑定模版的数据</summary>
        return window;
    },
    callback: null,
    onDomReady: function (root) {
        ///<summary>在派生类重写时，在创建的树上实例自己的控件</summary>
        if (this.callback) { this.callback(); }
    },
    onChildsReady: function () {
        if (this.childs && this.childs.length > 0) {
            Array.forEach(this.childs, function (c) { if (c.load) c.load(); });
        }
        this.load();
    }
}
Doo.Page.registerClass('Doo.Page', Doo.UserControlBase);
Doo.PageType = Doo.Page;
Doo.PageRoot = null;
Doo.PageInit = Function.emptyFunction;
Doo.PageAreas = null;
//Page
//doo_page
Doo$PageCreate = function (rootelement, callback) {
    //创建一个Doo页面，必须引用DataView.script.debug.js
    var source = rootelement.innerHTML;
    $Page = $create(Doo.PageType, { callback: callback, htmlcontent: source }, null, null, rootelement);
}
Sys.Application.add_init(function () {
    if (!Doo.PageRoot) Doo.PageRoot = document.body;
    Doo$PageCreate(Doo.PageRoot, Doo.PageInit);
    $Page.beginCreateChilds();
    if (Doo.PageAreas && Doo.PageAreas.length) {
        var pa = Doo.PageAreas;
        for (var i = 0; i < pa.length; i += 2) {
            var parent = pa[i + 1] ? window[pa[i + 1]] : $Page;
            Doo$AreaCreate(pa[i], parent);
        }
    }
    $Page.endCreateChilds();
});

Doo$AreaCreate = function (rootelementorid, parent) {
    ///<summary>在一个区域内创建控件集，并将创建的控件添加到上级</summary>
    ///<param name="parent" type="Doo.ControlBase"></param>
    if (typeof (rootelementorid) == 'string') rootelementorid = $get(rootelementorid);
    if (!rootelementorid) return;
    var source = rootelementorid.innerHTML;
    var cmtpl = { root: Doo.TemplateBinder.Compiler(source) };
    parent.beginCreateChilds();
    Doo.TemplateBinder.BindEx(parent, cmtpl, 0, function (frag) {
        rootelementorid.innerHTML = "";
        rootelementorid.appendChild(frag);
        parent.endCreateChilds();
    });


    //Doo.Utils.Dom.setHtmlAsync(rootelementorid, html, function () { parent.ondomready(); });
}

function $value(elem) {
    return elem.get_value ? elem.get_value() : elem.value;
}

function Doo$GetElem(elem, ctl) {
    if (ctl) elem = ctl.findChild(elem);
    else if (elem instanceof String) elem = $get(elem);

    return elem;
}

function $show(elem, ctl) {
    Doo$GetElem(elem, ctl).style.display = "";
}

function $hide(elem, ctl) {
    Doo$GetElem(elem, ctl).style.display = "none";
}